Jawaban yang diperbarui
Versi lebih bersih dan lebih pendek.
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' );
Jawaban lama
Menambahkan tanda centang untuk templat khusus jenis kiriman khusus di folder tema ke jawaban @Brainternet.
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');
Sekarang Anda dapat membiarkan pengguna plugin menyalin template dari plugin Anda ke tema mereka untuk menimpanya.
Dengan contoh ini, templat harus berada di direktori root dari plugin dan tema.