How does WordPress know which file to use when someone opens a blog post, a category archive or a missing page? The answer is the template hierarchy.
The template hierarchy is the set of rules WordPress follows to choose a template file for each request. It checks the most specific file first and then falls back to more general ones.
How does the template hierarchy work?
Think of it like ordering food at a restaurant. You first ask for your favorite dish. If it is not available, you settle for something similar, and finally you take whatever the chef has ready.
WordPress does the same with theme files. The last fallback is always index.php in classic themes, or index.html in block themes.
Template hierarchy examples
Here are a few common chains, from the most specific file to the most general one:
- Single post:
single-{post-type}-{slug}.php→single-{post-type}.php→single.php→singular.php→index.php - Page: custom template →
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 - 404 error:
404.php→index.php
For example, if you create category-news.php, only the category with the slug "news" uses that layout. Every other category still uses category.php or archive.php.
Why should you care about it?
It helps you customize one type of page without touching the others. You can design a better error page this way, as shown in our guide to create a custom 404 error page in WordPress.
Block themes follow the same rules. The main difference is that their templates are HTML files inside the templates folder, like single.html.
To see which template a page is using, the free Query Monitor plugin is a handy tool. It shows the exact file WordPress picked for the page you are viewing.
Add new template files to a child theme instead of the parent theme. That way, theme updates will not erase your work.
The template hierarchy is simply WordPress picking the best matching file for every page. That's pretty much it. Drop your questions in the comment section below, and we will try to answer them.