Episode 19 of 32
Template File Hierarchy
Understand how WordPress decides which template file to use — the template hierarchy and fallback system.
Template File Hierarchy
When someone visits a URL on your WordPress site, WordPress follows a template hierarchy — a set of rules that determines which PHP template file to use. Understanding this hierarchy is essential for building themes.
How the Hierarchy Works
WordPress looks for the most specific template file first, then falls back to more general ones:
- Check for the most specific template for the current page type
- If it doesn't exist, try the next one in the hierarchy
- If nothing matches, fall back to
index.php
Common Template Hierarchy Chains
| Page Type | WordPress Looks For (In Order) |
|---|---|
| Homepage | front-page.php → home.php → index.php |
| Single Post | single-{post-type}.php → single.php → singular.php → index.php |
| Page | page-{slug}.php → page-{id}.php → page.php → singular.php → index.php |
| Category | category-{slug}.php → category-{id}.php → category.php → archive.php → index.php |
| Tag | tag-{slug}.php → tag.php → archive.php → index.php |
| Author | author-{nicename}.php → author.php → archive.php → index.php |
| Search | search.php → index.php |
| 404 | 404.php → index.php |
Visual Example
A visitor goes to /category/javascript/. WordPress looks for:
category-javascript.php— specific to the "javascript" category slug ❌ Not foundcategory-5.php— specific to category ID 5 ❌ Not foundcategory.php— generic category template ❌ Not foundarchive.php— generic archive template ✅ Found! → Uses this
Homepage Templates
The homepage has two settings (Settings → Reading):
| Setting | Template Used |
|---|---|
| "Your latest posts" | front-page.php → home.php → index.php |
| "A static page" | front-page.php → selected page template → page.php |
front-page.php always wins for the homepage, regardless of the reading settings.
Template Files We'll Create
| File | What It Handles |
|---|---|
front-page.php | The homepage (hero + featured content) |
page.php | Static pages (About, Contact) |
single.php | Individual blog posts |
archive.php | Category, tag, and date archives |
search.php | Search results |
404.php | Page not found |
Conditional Tags
WordPress also provides conditional tags to check the current page type:
<?php if (is_front_page()) : ?>
<!-- Homepage-specific content -->
<?php elseif (is_single()) : ?>
<!-- Single post content -->
<?php elseif (is_page()) : ?>
<!-- Page content -->
<?php endif; ?>
Key Takeaways
- WordPress uses a template hierarchy to decide which template file to load
- It goes from most specific to most general, always falling back to
index.php front-page.phpalways controls the homepage display- Archive templates handle categories, tags, dates, and authors
- Understanding the hierarchy helps you create the right template for each page type