Skip to content

WP Template Hierarchy

WordPress Template Hierarchy

WordPress Documentation on the WordPress Template Hierarchy

The template hierarchy is the order in which WordPress template files are checked for a page.

If you are unsure of what template a page on the WordPress site is using you can download the Query Monitor Plugin. If you open the Query Monitor and switch to the Template tab it will outline the path along the template hierarchy that is being searched for by WordPress to build that page.

Using Query Monitor to find the template a page is using

On the page above for example if you look at the Template Hierarchy listed in the query monitor the order of events would go like this:

  • WordPress looks for a template file for single-tribe_events-gravel-camp-floyd-at-crooked-mountain.php (single-$posttype-$slug.php on the template hierarchy) but doesn't find it.

  • WordPress looks for single-tribe_events.php (single-$posttype.php) but doesn't find it (although we do have a single-tribe_events.twig file in this site - we'll circle back to this).

  • WordPress looks for single.php but doesn't find it.

  • WordPress looks for singular.php but doesn't find it.

  • WordPress looks finds index.php, the main theme template file, and renders it on the page.

Then above the hierarchy Query Monitor tells us that index.php is the template being used on this page.

Query Monitor also helps us by telling us which other template files are used throughout the page. In the column second from the right you can see the twig template files for the blocks that have been dropped on this page, and then at the very bottom you can also see that it is using the single-tribe_events.twig template. This is similar to the php file that was looked for in the template hierarchy above. The site in the screenshot above was built on our boilerplate, Origins, and og-core has a built-in router for loading the twig template of a page based on the WordPress Template hierarchy.

class TimberHierarchy {
    private $hierarchy;
    private $wp_query;
    private $context_provider;
    public function __construct(Hierarchy $hierarchy, $wp_query, ContextProvider $context_provider) {
        $this->wp_query = $wp_query;
        $this->hierarchy = $hierarchy;
        $this->context_provider = $context_provider;
    }
    public function templates($wp_query) {
        return $this->hierarchy->templates($wp_query);
    }
    public function render($templates, $context) {
        Timber::render($templates, $context);
    }

    public function load() {
        $templates = $this->templates($this->wp_query);
        $context = $this->context_provider->load($templates);
        $templates = array_map(function ($template) {
            return $template . ".twig";
        }, $templates);
        $this->render($templates, $context);
    }
}

$timber_hierarchy = new TimberHierarchy(new Hierarchy(), $wp_query, new ContextProvider());

$timber_hierarchy->load();