If you’re running a website covering news based on many different categories then you might want to use custom templates for posts based on each or multiple categories. If there are different post formats then you can also use custom templates for post formats.
Using A Different Post Template
For example, we will create a different post template for wordpress category of our site. Create a single.php file for your category and name it single-wordpress.php. Drop that file to the root of your current WordPress theme.
Now add the following snippet:
add_action('template_include', 'load_single_template');
function load_single_template($template) {
$new_template = '';
// single post template
if( is_single() ) {
global $post;
// 'wordpress' is category slugs
if( has_term('wordpress', 'category', $post) ) {
// use template file single-wordpress.php
$new_template = locate_template(array('single-wordpress.php' ));
}
}
return ('' != $new_template) ? $new_template : $template;
}
Code language: PHP (php)
This code snippet will take the posts assigned with the wordpress category and it will use single-wordpress.php file for it.
That’s it! You can repeat the process for other categories too.
Good tips Hardeep, I have a question.. what if you have 30 – 50 categories for big sites, your code won’t be able to scale it right?
It will work even with a zillion categories. Just add as many categories you want with the following code:
if( has_term('wordpress', 'category', $post) ) {
// use template file single-wordpress.php
$new_template = locate_template(array('single-wordpress.php' ));
}