WordPress’ Template File Hierarchy Explained

Whilst doing some client work recently I needed to display a slightly different archive for each category. The solution, I thought, was to throw if statements (ie if is category archive for ‘Cheese’ then use, else if is ‘Bananas’ use this etc etc) at the category.php file. The trouble was, after doing this twice, it became clear that it was getting very quickly impractical.

pyramid

This left me rather stumped, and after a bit of pondering, I thought the only solution was to create a load of pages and use custom page templates. Turns out I was wrong. WordPress, of course, has a better solution, as I found out the other day…

When WordPress loads any page, it looks at the theme files and if there is a file for the specific page that is loading, it uses that. If there isn’t, it will look for the next template file down the hierarchy. This is the WordPress template file hierarchy. I’ll run through all the hierarchies later, but going back to my little problem, it turns out the hierarchy for category archives is category-id.php, category.php, archive.php then index.php. This means I’ve got a solution! By creating a separate page for each category id, I can have my slightly different code without throwing if statements all over the place! Good ‘ol WordPress. Always got a smart answer!

I digress. Here are the template hierarhies:

Homepage

home.php, index.php

Single Post

single.php, index.php

Pages

(page templates), page.php, index.php

Category archive

category-id.php, category.php, archive.php, index.php

Author archive

author.php, archive.php, index.php

Date archive

date.php, archive.php, index.php

Tag archive

tag-slug.php, tag.php, archive.php, index.php

Search

search.php, index.php

404

404.php, index.php

After writing this, I found the codex has a great diagram:

http://codex.wordpress.org/Template_Hierarchy

http://codex.wordpress.org/Template_Hierarchy

It’s amazing all the little features WordPress has that you just didn’t know about! Any awesome tips you’ve got? Why not share said tips with the world by leaving a comment below.


8 Responses

Comments

  • Ivan Novak says:

    Consistently great articles. Thanks for the useful information. You have a loyal subscriber here!

    -Ivan

  • Indrek says:

    I know this question will be in the wrong place but I did’t find any better place for it.

    I’d like to know how you’ve done the replying part to comments? I mean when you click on Reply and it just moves to the commenting form, adds the cancel link etc.

    I’ve been tweaking my theme to use threaded comments but I’ve gotten only so far where clicking Reply moves the commenting form right after the parent comment. But I don’t like that method. I love yours 🙂

    Couldn’t find anything such in your source code or JS files also.

    Hope you’ll help me Alex 🙂
    .-= Indrek´s last blog ..Shortening Links – Which Service To Use? =-.

Pingbacks