0

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');
4
  • Can't you just use single-{post_type}.php per Theme Developer Handbook?
    – kero
    Dec 15, 2021 at 14:50
  • I would, but this is a plugin, not a custom theme, so I don't think that would work, would it? If it would work, that would be a nice fallback, but I would prefer to be able to put all the templates into a templates folder instead.
    – kloddant
    Dec 15, 2021 at 15:08
  • You could just POST an extra variable and check for its presence if $post is null.
    – WebElaine
    Dec 15, 2021 at 15:52
  • That would work, thanks! I do want to keep my form logic and hooks separate though, ideally, so this is a good backup, but I will keep looking for now.
    – kloddant
    Dec 15, 2021 at 18:15

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.