Custom Category Templates on a Archive or Index page.

April 23, 2008 by aaron

On my home page and in my archives, I use a custom category template to display asides and news articles. This is very easy to do and it only takes a couple seconds of work to create custom category templates in any WordPress theme.

The first step is to add the following to your current theme’s index.php loop after the line that looks like <?php while (have_posts()) : the_post(); ?>, but before any other code.

<?php $cat_temp = cat_loop();?>
    <?php if($cat_temp && is_numeric($cat_temp)){?>
        <?php include(&#039;loops/cat_&#039;.$cat_temp.&#039;.php&#039;);?>
    <?php }else{ ?>

Then add } just before the line endwhile.

The next step is to add the following to your theme’s functions.php file (you may have to create a file with the same name):

function cat_loop(){
    global $blog_id,$post, $wp_version;
        if($wp_version >= 2.3){
            global $object_term_cache;
            $array = $object_term_cache[$blog_id][$post->ID][&#039;category&#039;];
            global $category_cache;
            $array = $category_cache[$blog_id][$post->ID];
        while (list($cat) = each($array)) {
                return $cat;

This can be modified to look at author’s also. Now the only thing you have to do is to create a folder named “loops” in your theme’s folder, and then create a new file with a new “loop” — excluding the while and endwhile parts — and name it cat_xxx.php where xxx is the id of the category the loops is for.

This can be repeated for single.php, archive.php, or anywhere else a custom loop is useful. You can even use something similar for individual posts or pages.

A post may be in multiple categories, but it will only use the first custom template it finds, so make sure the post is in only one specially styled category at a time.

Categorized as:
comments powered by Disqus