Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

The template hierarchy

A theme may have one index.php for every case, but usually an article, a page, a category and a search look different. WordPress picks the template file itself from the kind of page being opened. The order in which it looks for files is called the template hierarchy.

The main templates

FileUsed for
front-page.phpThe site's front page
home.phpThe blog posts feed
single.phpA single post
page.phpA single page
archive.phpLists: category, tag, author, date
category.phpA category list
search.phpSearch results
404.phpPage not found
index.phpAnything no file was found for

From specific to general

WordPress checks files from the most specific to the most general and takes the first one that exists. For a category with the slug news and the number 5 the order is:

category-news.php → category-5.php → category.php → archive.php → index.php

For a post of the "book" type:

single-book.php → single.php → singular.php → index.php

That is why a theme starts with index.php, and other files are added as needed.

A template for one page

A page with the slug contact can have a file of its own — page-contact.php. It applies to that page only:

<?php
// page-contact.php
 
get_header();
?>
 
<main class="contact">
    <h1><?php the_title(); ?></h1>
    <?php the_content(); ?>
 
    <p>Phone: +1 202 555 0123</p>
</main>
 
<?php
get_footer();

A selectable template

A template that an editor chooses in the dashboard is marked with a comment:

<?php
/**
 * Template Name: Page without a sidebar
 */
// template-wide.php
 
get_header();
?>
 
<main class="wide">
    <?php
    while (have_posts()) :
        the_post();
        the_content();
    endwhile;
    ?>
</main>
 
<?php
get_footer();

It appears in the "Template" list when a page is edited.

The 404 page

<?php
// 404.php
 
get_header();
?>
 
<main>
    <h1>Page not found</h1>
    <p>Try searching:</p>
    <?php get_search_form(); ?>
</main>
 
<?php
get_footer();

Conditional tags

Inside a shared template the kind of page is checked with conditional tags:

<?php
// header.php
 
if (is_front_page()) {
    echo '<p class="tagline">' . esc_html(get_bloginfo('description')) . '</p>';
}
FunctionWhen it is true
is_front_page()The front page
is_single()A single post
is_page('contact')A page; a slug can be given
is_category(), is_tag()A category or tag list
is_archive()Any list
is_search()Search results
is_404()Page not found
is_user_logged_in()The visitor is logged in

Common mistake

front-page.php and home.php are easy to mix up. front-page.php is the site's front page, whatever is on it. home.php is the posts feed, which may live at /blog. If a static page is set as the front page under "Settings → Reading", home.php does not apply to it. The Query Monitor plugin shows which template is in use right now.

Thanks for reading!

Donate to the site — we work hard for you.