更新的答案更简洁、更简短。
function load_movie_template( $template ) {
global $post;
if ( \'movie\' === $post->post_type && locate_template( array( \'single-movie.php\' ) ) !== $template ) {
/*
* This is a \'movie\' post
* AND a \'single movie template\' is not found on
* theme or child theme directories, so load it
* from our plugin directory.
*/
return plugin_dir_path( __FILE__ ) . \'single-movie.php\';
}
return $template;
}
add_filter( \'single_template\', \'load_movie_template\' );
旧答案在主题文件夹中为@Brainternet answer添加了一个自定义帖子类型特定模板的检查。
function load_cpt_template($template) {
global $post;
// Is this a "my-custom-post-type" post?
if ($post->post_type == "my-custom-post-type"){
//Your plugin path
$plugin_path = plugin_dir_path( __FILE__ );
// The name of custom post type single template
$template_name = \'single-my-custom-post-type.php\';
// A specific single template for my custom post type exists in theme folder? Or it also doesn\'t exist in my plugin?
if($template === get_stylesheet_directory() . \'/\' . $template_name
|| !file_exists($plugin_path . $template_name)) {
//Then return "single.php" or "single-my-custom-post-type.php" from theme directory.
return $template;
}
// If not, return my plugin custom post type template.
return $plugin_path . $template_name;
}
//This is not my custom post type, do nothing with $template
return $template;
}
add_filter(\'single_template\', \'load_cpt_template\');
现在,您可以让插件用户将模板从插件复制到他们的主题以覆盖它。
在本例中,模板必须位于插件和主题的根目录中。