How do I use a plugin to swap out the template file for a custom post type?

I’m trying to apply a filter for a custom post type and give it a different template. All from within a plugin. However, despite confirming that add_hooks() is called (everything else works in that area), the filter is flatly ignored.

I can only guess that I got something wrong as it looks like the filter is never applied. I know it is not because I put an else/die in there. It should either give me my template or die (right?) but it ignores me. How do I do this correctly?

class some_cool_new_stuff{

public function __construct(){
$this->add_hooks();
}

public function page_template( $page_template ) {
if ( is_page( ‘my_lovely_post_type’ ) ) {
$page_template = MY_CUSTOM_CONST_FOR_PLUGIN_DIR . ‘templates/business-page.php’; // this does not happen but the path is 100% correct
}else{
die(“Help me, I’m going to die!!”); // this never happens
}
return $page_template;
}

public function add_hooks(){
// …
add_action( ‘init’, array($this,’awesome_function’) );
add_filter( ‘page_template’, array($this,’page_template’) );
// …
}

// …

}

Here is some other stuff that doesn’t work for me:

add_filter( ‘my_lovely_post_type_template’, array($this,’page_template’) );
add_filter( ‘template_include’, array($this,’page_template’) );

Read more here:: How do I use a plugin to swap out the template file for a custom post type?

Leave a Reply

Your email address will not be published. Required fields are marked *