Using WordPress ‘get_template_hierarchy()’ PHP function

The get_template_hierarchy() WordPress PHP function gets the template hierarchy for a given template slug to be created. Always add index as the last fallback template.

Usage

get_template_hierarchy( $slug, $is_custom = false, $template_prefix = '' )

Example:

$hierarchy = get_template_hierarchy('taxonomy-books');
print_r($hierarchy);

Output:

Array
(
    [0] => taxonomy-books.php
    [1] => taxonomy.php
    [2] => archive.php
    [3] => index.php
)

Parameters

  • $slug string (Required): The template slug to be created.
  • $is_custom boolean (Optional): Indicates if a template is custom or part of the template hierarchy. Default: false
  • $template_prefix string (Optional): The template prefix for the created template. Used to extract the main template type, e.g., in taxonomy-books the taxonomy is extracted. Default: ”

More information

See WordPress Developer Resources: get_template_hierarchy()

Examples

Get hierarchy for a single post

This example gets the template hierarchy for a single post template.

$hierarchy = get_template_hierarchy('single');
print_r($hierarchy);

Get hierarchy for a custom page

This example gets the template hierarchy for a custom page template.

$hierarchy = get_template_hierarchy('page', true, 'page-template');
print_r($hierarchy);

Get hierarchy for a category template

This example gets the template hierarchy for a category template.

$hierarchy = get_template_hierarchy('category');
print_r($hierarchy);

Get hierarchy for a tag template

This example gets the template hierarchy for a tag template.

$hierarchy = get_template_hierarchy('tag');
print_r($hierarchy);

Get hierarchy for an author template

This example gets the template hierarchy for an author template.

$hierarchy = get_template_hierarchy('author');
print_r($hierarchy);