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.
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:
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.