WordPress Tip: Setting up Category Specific Templates

Recently I had to develop a WordPress blog that has multiple categories. We wanted to be able to show different design elements on the category template for specific templates.

It would seem like you need to create some custom code to show a different template based on the category ID or slug. Actually, it’s pretty simple. WordPress has a template hierarchy that is used to find which template file to use. All you have to do is create a category file with the following file name structure:

category-[slug].php
category-[ID].php

Just fill in the slug or category ID from your WordPress and you’re ready to go. For example, category-news.php would be used only for posts using in the ‘news’ category. If you do not have a category-[slug].php, WordPress will look for category-[id].php

Simple!

To take it one step further, we wanted to be able to load a different template for a single post in a specific category.

First you need to edit your single.php file. I would recommened creating a backup of your current single.php since this step will remove all code from your current version.

WordPress looks at the single.php file to display the content of a post. Based on the category ID we will redirect WordPress to a custom template instead of using the standard single.php. Here’s how it would work:

    <?php
    $post = $wp_query->post;
    if ( in_category(‘2’) ) {
    include(TEMPLATEPATH . ‘/news.php’);

    } else {
    include(TEMPLATEPATH . ‘/blogpost.php’);
    }
    ?>

In short, the first two lines setup a query. The second line tells WordPress that if the post is associated to category 2 then load the new.php as the template file. The next line tells WordPress to load the blogpost.php as the default.

Creating multiple templates is easy! Just use the “elseif” conditional tag and we can add an extra template file. You can use as many “elseif” statements as you need to match up your templates.

    <?php
    $post = $wp_query->post;
    if ( in_category(‘2’) ) {
    include(TEMPLATEPATH . ‘/news.php’);

    } elseif ( in_category(‘8’) ) {
    include(TEMPLATEPATH . ‘/events.php’);

    } else {
    include(TEMPLATEPATH . ‘/blogpost.php’);
    }
    ?>

Quick and painless!

No related posts.

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=""> <strike> <strong>