What is the best way (performance & code structure) to create a custom template for a WordPress Post, which belong to a specific category? I realized that you can’t just create single-catname.php
.
So far i tried two ways to change the template. But which one (or another one) is the best?
EDIT:
Any idea how to include all the sub/parent and so on categories to? I realized right now it only shows the main category...
1. Added to functions.php
function get_custom_cat_template($single_template) {
global $post;
if ( in_category( 'movies' )) {
$single_template = dirname( __FILE__ ) . '/single-movies.php';
}
return $single_template;
}
add_filter( "single_template", "get_custom_cat_template" ) ;
2. Put the following Code in to single.php (instead of all other code) and create a single-template.php
(with the code from the single.php) & a custom single-movies.php
<?php
if(has_term('movies', 'category', $post)) {
get_template_part('single-movies', 'movies');
} else {
// use default template file single-template.php
get_template_part('single-template');
}
?>