How to use a dedicated template for the Custom Post Type from a plugin?

I’m working through this tutorial on Custom Post Types (in a plugin) wherein the author demonstrates how to force the use of a dedicated template for the Custom Post Type. The author states thus:

The code (below) searches for the template single-movie-reviews.php in the current theme directory. If it is not found then it looks into the plugin directory for the template, which we supply as a part of the plugin. The template_include hook was used to change the default behavior and enforce a specific template.

Read More

Step 1: Added this code to my plugin-name.php file

add_filter( 'template_include', 'include_reviews_template', 1 );
function include_reviews_template(){
    if ( get_post_type() == 'reviews' ) {
        if ( is_single() ) {
            // checks if the file exists in the theme first,
            // otherwise serve the file from the plugin
            if ( $theme_file = locate_template( array( 'single-movie-reviews.php' ) ) ) {
                    $template_path = $theme_file;
                } else {
                    $template_path = plugin_dir_path( __FILE__ ) . '/templates/single-movie-reviews.php';
            }
        }
    }
    return $template_path;
}

Step 2: Create the single-{custom-post-type}.php file.

Next, I created the requisite single-movie-reviews.php file and added it to '/my-plugin/templates/' directory.

The author adds the following:

Note: You need to create a new page from the dashboard using the newly
created template.

The Problems

  1. The Page template does NOT show in the dashboard
  2. When I visited the post I created using the Custom Post Type, it does show the post using the page template from the plugin. However… every other page (i.e. pages NOT using the CPT) now show a blank white screen (as though it cannot find the proper template to use).

So what am I doing wrong?

Please advise

Related posts

1 comment

  1. Change this line:

    function include_reviews_template(){
    

    To this:

    function include_reviews_template( $template_path ) {
    

    When get_post_type() == 'reviews' is false you are returning an unset variable ($template_path). This change should send the value passed to the function by WordPress.

Comments are closed.