Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 68 ยท Classic Themes and the Template Hierarchy

The Template Hierarchy

Learn how WordPress chooses a template file for posts, pages, archives, search and 404 pages - specificity chains, custom templates, template_include and block themes.

When a visitor requests a URL, WordPress has to decide which file in your theme will print the page. It does not guess and it does not use a routing table you write. It follows the template hierarchy: for each type of page, a fixed list of file names, from the most specific to the most general. WordPress picks the first file on that list that exists in your theme. If none of the specific ones exist, it ends at index.php, which every theme must have.

Once you know the hierarchy, you can answer "which file do I edit to change this page?" for any URL, and you can add a specialized template just by creating a file with the right name. This lesson walks through the chains for the common page types, shows custom templates and the template_include filter, and explains why block themes work the same way.

The runnable examples are plain-PHP stand-ins for WordPress's resolver. The real code lives in wp-includes/template.php and handles more cases, such as attachments and embeds. The file-name chains below are the real WordPress ones for the common page types.

From URL to template

The decision happens in three steps. First, WordPress turns the URL into query variables and runs the main query. Second, the query sets flags such as "this is a category archive". Third, in a file called template-loader.php, WordPress checks those flags in a fixed order and asks for a list of candidate file names for the first flag that is true.

flowchart LR
    A["URL"] --> B["Query variables"]
    B --> C["Main query flags<br/>(is_single, is_category, ...)"]
    C --> D["Candidate file names<br/>most specific first"]
    D --> E["First file that exists"]
    E --> F["Template runs the Loop"]

WordPress converts the request into flags, lists candidate files and picks the first one that exists.

The checks run roughly in this order: 404, search, front page, home (blog index), post type archive, taxonomy, attachment, single post, page, singular, category, tag, author, date, then generic archive. You do not need to memorize the order. Think of it as "the most specific kind of page wins".

The chains you will use

Each list below runs from most specific (left) to the final fallback (right).

Single post (a post, or a custom post type named book):

TEXT
single-book-the-hobbit.php  ->  single-book.php  ->  single.php  ->  singular.php  ->  index.php

For a regular post, replace book with post: single-post-{slug}.php, single-post.php, single.php.

Page:

TEXT
(custom template)  ->  page-about.php  ->  page-42.php  ->  page.php  ->  singular.php  ->  index.php

The page-{slug}.php and page-{id}.php names let you restyle one page without touching the others.

Category, tag and custom taxonomy archives:

TEXT
category-news.php  ->  category-7.php  ->  category.php  ->  archive.php  ->  index.php
tag-php.php        ->  tag-12.php      ->  tag.php       ->  archive.php  ->  index.php
taxonomy-genre-jazz.php -> taxonomy-genre.php -> taxonomy.php -> archive.php -> index.php

Author, date and custom post type archives:

TEXT
author-sam.php  ->  author-3.php  ->  author.php  ->  archive.php  ->  index.php
date.php  ->  archive.php  ->  index.php
archive-book.php  ->  archive.php  ->  index.php

Search and 404:

TEXT
search.php  ->  index.php
404.php     ->  index.php

Front page and blog index:

TEXT
front-page.php  (wins for the site's front page, in both settings)
home.php  ->  index.php                  (the blog posts index)

If the settings say "Your homepage displays: a static page", the posts page uses the home.php chain and the front page first tries front-page.php, then falls into the page chain. If the settings say "latest posts", front-page.php is still checked first, then home.php, then index.php. The names home and front-page match the conditional tags is_home() and is_front_page().

Notice that singular.php sits between single.php/page.php and index.php. It is a shared fallback for any single post type, handy when posts and pages look alike. archive.php plays the same role for all archives.

A hierarchy resolver you can run

This stand-in builds the candidate list for a request and picks the first file that exists in a pretend theme. The $files list is the theme's directory listing.

PHP A mini template hierarchy resolver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The "Contact" page falls back from page-contact.php and page-9.php to page.php. The "reviews" category falls back to archive.php because the theme has no category-reviews.php, category-8.php or category.php. The book archive finds archive.php and the unknown URL ends at index.php because the theme has no 404.php. Create any of the missing files and the result changes at once, with no registration step.

Custom page templates

Sometimes a particular page needs its own layout, but the page's slug is not stable enough to hardcode in a file name. A custom page template solves this. You add a file with a special comment at the top, and editors can pick it from the Page settings:

PHP
<?php
/**
 * Template Name: Landing Page
 * Template Post Type: page, book
 */

get_header();
// ... a custom layout ...
get_footer();

When an editor chooses "Landing Page", WordPress stores the file name in the page's _wp_page_template meta value. The hierarchy then puts that file first in the list (the "custom template" entry in the page chain above). Template Post Type makes the same template available for other post types, such as book.

Also notice that page-{slug}.php is chosen automatically by name, while a custom template is chosen explicitly by an editor. Use file-name templates for developer decisions, and custom templates when editors need the choice.

Changing the choice with template_include

After WordPress has found a template, it runs one last filter, template_include. A callback receives the full path of the chosen file and returns the path that will actually be loaded:

PHP
<?php
add_filter( 'template_include', function ( string $template ): string {
    if ( is_singular( 'book' ) && is_user_logged_in() === false ) {
        $locked = get_theme_file_path( 'templates-extra/book-login.php' );
        if ( file_exists( $locked ) ) {
            return $locked;
        }
    }
    return $template;
} );

Plugins use this filter to supply their own templates, such as a booking page. A filter must always return a path. Returning nothing would load no template at all. There are also narrower filters, such as single_template, page_template and category_template, which replace the result for just one page type. For more on filters, see actions and filters.

PHP template_include as a last-chance filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Block themes use the same hierarchy

Block themes do not use PHP files for pages. Their templates are HTML files in a templates/ folder: templates/single.html, templates/page.html, templates/archive.html, templates/404.html and so on. The names and the fallback logic are exactly the ones above. A request for a category still tries category-news, then category-7, then category, then archive, then index. The only differences are the file extension (.html), the lookup place (templates/), and that editors can create overriding versions in the Site Editor, which are stored in the database and win over the theme's file.

You will build these in block themes: the big picture and block templates and template parts. Learning the hierarchy once pays off for both kinds of theme.

Common mistakes

  • Misnaming files. page_about.php or Page-About.php is never matched. Use lowercase, hyphens and the exact prefixes.
  • Confusing the slug with the title. page-about-us.php matches a page whose slug is about-us, not whose title is "About Us".
  • Editing index.php for everything. Create specific files so each page type stays simple.
  • Forgetting that front-page.php always wins for the front page, even when home.php exists.
  • Returning nothing from a template_include callback.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A visitor opens a category archive with the slug "news" and ID 7. Which file does WordPress try first?

    The chain is category-{slug}.php, category-{id}.php, category.php, archive.php, index.php. The slug version is the most specific.
  2. 2. Which file is the last fallback for every type of page?

    index.php is required in every theme and is the final fallback of every chain.
  3. 3. What does the template_include filter receive and return?

    template_include gets the path WordPress selected and must return the path that will be loaded.
  4. 4. How do block themes choose a template for a single post?

    Block themes use the same file-name logic, with HTML files in the templates folder.
  5. 5. Which file can restyle only the page with slug "contact" without a custom template header?

    page-{slug}.php is matched automatically by the page template chain.

Summary

  • WordPress picks a template by walking a fixed list of file names, most specific first, and takes the first that exists.
  • index.php is the last fallback; singular.php and archive.php are shared fallbacks for single and archive pages.
  • Slug and ID based names such as page-about.php, category-7.php and single-book.php restyle single items.
  • Custom page templates use a Template Name: header and are chosen by editors; template_include can change the final choice.
  • Block themes use the same names and fallbacks with HTML files in templates/.
  • The runnable resolvers are plain-PHP stand-ins that follow the real file-name chains.

Next: Your First Classic Theme