How to use template_include hook with form submission?

I'm writing a plugin that uses the template_include hook to use a custom template for a custom post type. This works with GET requests, but with POST requests, it 404s because the $post variable is null within this hook in POST requests. How do I fix this so that I can use this custom template for both GET and POST requests?

namespace mynamespace;

class MyPlugin {

    public static function template_include($template) {
        global $post;
        var_dump($post); //$post exists for GET requests but is null for POST requests.
        var_dump(get_queried_object()); 
        // Same with get_queried_object.  
        // So for POST requests, I have no way of telling if this is the page of the specific 
        // custom post type that I want to target here.
        if ($post and $post-post_type == 'thing') { // true for GET, false for POST
            return plugin_dir_path( __FILE__ ) . 'templates/thing.php';
        }
        else if (get_query_var('post_type') == 'thing') { // true for GET, false for POST
            return plugin_dir_path( __FILE__ ) . 'templates/thing.php';
        }
        return $template;
    }

}

add_filter('template_include', '\mynamespace\MyPlugin::template_include');

Topic template-include hooks plugins custom-post-types Wordpress

Category Web


It turns out that $wp->query_vars["post_type"] contains the data I need, regardless of whether the request method is GET or POST.

namespace mynamespace;

class MyPlugin {

    public static function template_include($template) {
        global $wp;
        if ($wp->query_vars["post_type"] == 'thing') {
            return plugin_dir_path( __FILE__ ) . 'templates/thing.php';
        }
        return $template;
    }
}

add_filter('template_include', '\mynamespace\MyPlugin::template_include');

Also, it appears that the reason this problem occurred in the first place is because I had named a field in the form with the same name as the custom post type. If I name the form field something different, then there is no issue.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.