mattmedia.net

How to Set Up Custom Wordpress Category Templates in Four Easy Steps

Posted by Matt on 10-09-07 | del.icio.us:How to Set Up Custom Wordpress Category Templates in Four Easy Steps digg:How to Set Up Custom Wordpress Category Templates in Four Easy Steps newsvine:How to Set Up Custom Wordpress Category Templates in Four Easy Steps reddit:How to Set Up Custom Wordpress Category Templates in Four Easy Steps fark:How to Set Up Custom Wordpress Category Templates in Four Easy Steps Y!:How to Set Up Custom Wordpress Category Templates in Four Easy Steps

In a recent project, I needed to distinguish blog-style posts from longer, stand-alone articles in WordPress. The blog posts needed to look one way, and the articles, another. One type needed to look like a pretty typical blog post, but the other needed to look more like a New York Times story page. My basic goal was to categorize stories as either "posts" or "articles," and let WordPress apply the proper template for me. Seemed like it should be easy… until I tried to figure out how to make it work.

I found the explanations in the WordPress codex confusing and unhelpful. I searched around for some other solutions and didn’t find much to help me sort this out. Most articles or posts on the matter were knee-deep in code and long scripts. Finally, I found this post by Lorelle on "Creating Multiple Single Posts for Different Categories" which was tremendously useful. However, I still found the explanation a bit fuzzy. I sorted it out, but think a clearer take on this might help other similarly baffled WordPress users:

Step 1: Design two (or more) custom templates. A good way to start is to copy the "single.php" file from the default templete and modify it to suit your needs. In my case, I set up one template called "blogpost.php" and another called "article.php." I prefer to have descriptive template file names. Need more help? I’ve found Ben Gillbanks’ short tutorial on creating custom templates useful. Ok, so once you’ve got your custom templates worked up, copy them into your theme directory.

Step 2: Back-up your single.php file. Since the next step will destroy your single.php file as it currently exists, take a few seconds and make a copy of your working file, just in case something goes wrong. You can always replace your modified single.php file with the original to change everything back to the way it was before you started tinkering. Better safe than sorry, right?

Step 2: Turn the "single.php" into doorway to your custom templates. In a normal WordPress theme, the "single.php" file, also known as the "Single Post" template, takes a post and styles it with this basic template. But if you want to use multiple post templates, you can use this file to help WordPress understand which one to use. The WordPress engine looks at the single.php file to style your post’s content, but since it is a PHP file, you can use it to redirect it to your custom templates.

So what we’re going to do is replace the single.php file with some very short code that tells WordPress to check the category of a post and then load the appropriate template. You use the categoryID number from the Manage | Categories tab to identify the correct category. Here’s how the code would look:

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

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

So let’s break this down. the first two lines set up a query. The second line tells WordPress that if a post matches category 5 (which happens to be the ID for my "article" category… your number would vary, obviously), load the template "article.php". The next lines say, basically, "ok, so if this isn’t an article, it’s a blog post, so go ahead and load "blogpost.php".

But what if you have more than two category-based templates? No problem. Your new best friend is a little conditional tag called “elseif.” Here’s how that would work:

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

} elseif ( in_category(‘6’) ) {
include(TEMPLATEPATH . ‘/column.php’);

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

So this three-way query tells WordPress, "if a post is category 5 (an article), load the article.php template, if it’s not category 5, then check to see if it is category 6 (a column) and load the column.php template if it matches that, otherwise, it must be a post, so load the blogpost.php template." You can set up as many “elseif” statesments as you need to match the number of custom post templates you want to use.

Go ahead and save your single.php file. That short snippet of code is all you need. You’re almost done.

4. Give it a test. If you did everything right, the single.php should act like a traffic cop and direct posts to the correct template, depending on their category. Test posts by category and see how they display. If the templates seem broken or no post shows up, you may be missing a bracket or semicolon someplace in your single.php file. Go back and double check it. Conditional statements (if, else, and elseif) can be a bit confusing, so it can help to check the syntax here. You might also need to make sure your custom templates don’t have any odd code that might mess up the display.

Hope this helps. Drop me a line if you have questions or comments…



22 responses to “How to Set Up Custom Wordpress Category Templates in Four Easy Steps”

  • Lorelle says:

    Another explanation that might be clearer than mine, and a lot simpler, is in Using WordPress Categories To Style Posts, a much easier method than both of ours.

  • Andreas says:

    Dude! Thanks alot. I never got that the code should be replaced in single.php from the explanation given on the codex. Thanks for making this clear.

  • Andreas says:

    Dude! Thanks alot. I never got that the code should be replaced in single.php from the explanation given on the codex. Thanks for making this clear.

  • barbie says:

    Thanks for making this clear

  • barbie says:

    Thanks

  • santafeliving says:

    Hi - great info, very nicely explained. One further question. What if you have several categories for which you want to use specific templates (as above) but then want all other categories (which might be created on the fly) to have the standard look that single.php would have provided before it was changed? Not sure if that’s doable - but thought I’d ask.
    Thanks!

  • santafeliving says:

    Sorry, figured it out. Just one of those “duh” moments!

  • Selene M. Bowlby says:

    Works like a charm! Thank you so much for this!

  • Harald Johnsen says:

    That’s pretty cool, I’m going to use this for sure.

    Great stuff. Thanks a lot. I’ll let others know (and thanks to Selene M. Bowlby who alerted me to this on Twitter).

  • How to use WordPress as a Truly Customized CMS (Multiple Headers, Footers, Sidebars and more!) | Web Designer + Front-End Web Developer | Selene M. Bowlby says:

    […] How to Resource Link… Creating Your Own Page Templates […]

  • JamieO says:

    Another slightly less complex alternative is to use the Idealien Category Enhancements plugin. It allows you to select templates through the admin consoles’ manage > categories window. Think of it as all the same customizability of page templates for either category.php or single.php without having to go and modify the php each time you add a new category or template.

  • Carl says:

    Hi,

    I need some help, if possible. I have a blog that covers several different topics: Travel, Sports, etc…

    I only want the header image to change for the category and the post.

    For example, the homepage will have a header image when a visitor arrives.

    If they click on the “Travel” category, the category page will show a header image of an airplane.

    In the Travel category, I have a subcategory about Hawaii with posts. If someone clicks on a post in the Hawaii subcategory, the header image will show a picture of Hawaii.

    I think I need to somehow customize the “archives.php” in my template but not sure how to do it.

    I just want to control the header image of the categories and subcategories, the rest of the template should remain the same.

    Is there a way to implement this using the information above?

    Thanks in advance for your help

  • John says:

    Thanks for the tutorial Matt. To get this to work for me (in WP 2.6.2) I had to alter my template files (copies of single.php) thus:

    Replace the following:

    With:

    where ‘cat=3’ is the id of your category, and ‘posts_per_page=-1’ are the number of posts to display, in this case all.

    Without the above I couldn’t get the template to display posts; the appropriate template for each category would load fine, but no posts would be displayed.

    I am definitely no expert in PHP, so it is quite likely this can be refined/improved.

  • another matt says:

    i’m getting lost on step 2….
    oops.. i meant - thanks fella. Big help! :)

  • Viebrapreah says:

    Hey,
    I am, John
    Nice site, verry informative
    check my site:

    http://ARcA8NEZ.spaces.live.com/

  • Atle says:

    This is just one hell of a great post :D

    BUT.. I would like to ask for some help, becaouse this actually does not work for me. Me template is using single.php for blogposts as normalt themes do, and I do not quite understand why this solution you provide us with over does’nt work for me.

    I just tried this as a test, so I created to files called “hei.php” and “hallo.php,” containing the code fra the “old” single.php. I try to open a blogpost, and this is my error:

    Warning: Division by zero in /home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaper/single.php on line 9 Warning: include(/home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaperphp?): failed to open stream: No such file or directory in /home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaper/single.php on line 9 Warning: include(): Failed opening ‘/home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaperphp?’ for inclusion (include_path=’.:’) in /home/secondpo/www/baredritt/wp-content/themes/FuckingNewspaper/single.php on line 9

    I don’t know what I could do with this… Perhaps you could help me out here? :)

    - Thanks in advance!

  • Atle says:

    To be a little bit more specific this is what I have in my single.php file when I get the error-message above:

    post;
    if ( in_category(‘5’) ) {
    include(TEMPLATEPATH . ‘/hei.php’);

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

    I am not a php-champion, so I am just not even sure if this is correct.. :(

  • Atle says:

    Sorry for just spamming up everything here, but I actually had to use just:

    post;
    if ( in_category(‘5’) ) {
    include(“hei.php”);

    } else {
    include(“hallo.php”);
    }
    ?>

    to make everything work. :)

  • Gradimir says:

    Ready to argue with the themes of education-all. All the same, you can very well write about it

  • Mark says:

    What happens if you don’t have a single.php file in Wordpress? I honestly don’t see one…

  • Martin says:

    Your a legend, cheers!

  • Tim says:

    I was trying to figure out how to do this and found your site while searching the net for solutions. Worked perfectly. Thanks a lot!


  • Got something to say?