Add Custom Post Templates for Specific Categories

Add Tool

How To Add Custom Post Templates for Specific Categories

Hi learner how are you? In this web developers resources I will inform you how to set Custom Post Templates for Specific 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:

<?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.

Source: Austin Matzko

Tags: category, Code, Development Tools, Php, single.php, Snippets, theme development, WordPress, WordPress snippets,

About Masum Billah

How To Add Custom Post Templates for Specific Categories 1stWebSuite website seo tool is a free website ranking tool site provides a lot of on page and off page seo useful tools for you. On this site, we have a large number of website ranking tools


Discuss about: Add Custom Post Templates for Specific Categories