Different post template for each category in wordpress

single.php is used to display posts of a categories in wordpress. Suppose you want to display each category with a different layout then you can add different template file for each category. You can use built in function “in_category” of wordpress. This function checks that the specific post assigned to which specific category. You can use this function in both loop and outside loop when ever single post requested.

<?php in_category( $category, $_post ) ?>

First parameter “$category” is must and it specified by id, slug or name of the category. Second parameter is “$_post”. It is optional parameter. Default value is current post in loop or query. If you want to use this tag in your wordpress website just post the following code in your “Single.php” file. If the post is in profile category it will include “single_profile.php”. Else if the post is in portfolio category it will include “single_portfolio.php” else it continues with normal loop.

<?php
if ( in_category('profile') ) {
	include 'single-profile.php';
} elseif ( in_category('portfolio') ) {
	include 'single-portfolio.php';
} else {
	// normal Loop
	if ( have_posts() ) : while ( have_posts() ) : the_post();
	// ...
}
?>




Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.