You can use this function to add category specific single template pages on your website. This goes in functions.php
You can define as many single templates as you want.
function wpse_category_single_template( $single_template ) {
global $post;
$all_cats = get_the_category();
if ( $all_cats[0]->cat_ID == '1' ) {
if ( file_exists(get_template_directory() . "/single-cat1.php") ) return get_template_directory() . "/single-cat1.php";
} elseif ( $all_cats[0]->cat_ID == '2' ) {
if ( file_exists(get_template_directory() . "/single-cat2.php") ) return get_template_directory() . "/single-cat2.php";
}
return $single_template;
}
add_filter( 'single_template', 'wpse_category_single_template' );
Here I used single-cat1.php
for category id 1 and single-cat2.php
for category id 2. You can name these single templates as you feel right.
This function also uses default fallback to single.php
if there is no single-cat1.php
or single-cat2.php
exists.
EDIT 1
I have been using above code on 2 of my websites and it’s working fine on latest version of WordPress.
Paste this in your functions.php
function show_template() {
global $template;
print_r($template);
}
add_action( 'wp_head', 'show_template' );
This will print the template file used on each page/post. Now access your website and see if correct template file is being used or not? If it’s still showing single.php
then there is something wrong with your code.
EDIT 2
Here is your code for that.
function wpse_category_single_template( $single_template ) {
global $post;
$all_cats = get_the_category();
if ( in_category(6) ) {
if ( file_exists(get_template_directory() . "/page-custom.php") ) {
return get_template_directory() . "/page-custom.php";
} else {
return get_template_directory() . "/page.php";
}
}
return $single_template;
}
add_filter( 'single_template', 'wpse_category_single_template' );