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.
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
- The Page template does NOT show in the dashboard
- 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
Change this line:
To this:
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.