Unique Single Post Templates for Different Categories

Hi learner how are your In this web developers resources I will inform you how to set Unique Single Post Templates for Different Categories. Here is an easy way to display custom post styles depending on the post’s category. With the following code, each single-view post will be displayed according to a template that is specific to the post’s category:

Single Post Templates for Unique Categories

<?php $post = $wp_query->post;
if (in_category('1')) {
} elseif (in_category('2')) {
} else {
} ?>

This code should be placed in your theme’s single.php file. As written, this code will display posts from the first category with the single template, single-01.php also, posts from the second category will be displayed with a single template named single-02.php finally, all other posts will be displayed via the default single template, single-default.php. Of course, you will want to customize the category IDs according to your own needs, and also you will want to create the customized single files as they are called. That’s all there is to it.

Having said that, here is an alternate version of the custom-post-template script:

<?php add_filter('single_template', create_function('$t', 'foreach((array) get_the_category() as $cat) { if (file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php")) return TEMPLATEPATH . "/single-{$cat->term_id}.php"; } return $t;')); ?>

Placed in your theme’s functions.php file, this alternate script checks all categories for the presence of a custom single template. Any category with a custom single-post template will then have its posts displayed with that template. If a post’s category does not feature a custom template, the default single.php template will be used. Note that this code will use the template for the first listed category of each post. Even so, you should only create custom post templates for categories that will always be mutually exclusive. That is, make sure that your posts aren’t in more than one custom-templates category.

Masum Billah has written 326 articles

Hi I am Md. Masum Billah Contributor of this website. I always like to share various things with other. In this website I am sharing web design related tips and tricks, necessary web development tools, source codes for beginner and advance web developer. You may join with us to help other who want to learn web design and development. Thank you for stay with.

Recommended Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>