Technology

In WordPress, create special templates for posts in a category

Posted by Pixafy Team

This tutorial is based on WordPress’ TwentyTen Theme.

The Category Template applies to the overall loop of your posts. And if you want posts within a certain category to display a different structure and style, then using a Category Template is the way to go. Now, when you click into each post, into it’s single post state, also known as permalink, if this is the only place you will need to style your single post, then going straight to loop-single.php and style there.

However, what happens if you’ve already styled this loop for something else on your site and you’d like to have different one? WordPress knows to replace the default loop.php with a Category Template based on its name. It does not work the same way for loop-single.php. So instead, we have to involve a bit of code customization.

The loop-single.php file is called in single.php, where it basically says, if this loop exists, use this for single posts:

<?php
/* Run the loop to output the post.
 * If you want to overload this in a child theme then include a file
 * called loop-single.php and that will be used instead.
 */
get_template_part( 'loop', 'single' );
?>

Now, let’s say your Category is called Press and you want a different loop-single template to take effect and it won’t interfere with the default loop-single. This is the perfect instance for a php if statement.

So instead of the above php that only calls for one file, you would write:

<?php if ( is_page('Press') ) {  //if it is in category Press
     get_template_part( 'loop', 'press' );  //use this loop template
} else { //if it is not category Press
     get_template_part( 'loop', 'single' ); //This is what wp does by default
} ?>

The file it calls if the category is Press will be loop-press.php (basically, merge the item in the first single quotes, ‘loop’, with the second, ‘press’, separated by a dash). If it is not category Press, it will call loop-single.php just like it would by default.

Keep in mind that the above example is using the name of the category, and not the slug or id. More about that can be found here and either one can be used. Together with Category Templates and this technique, you can have a different structure or style for your blog and a specific category, or if you’re really ambitious, for multiple categories.

Do you have tricks you use in WordPress to speed up development?  Share them with us in the comments!

More on WordPress:

Questions or comments? Share them below, or tweet us @Pixafy!