Function and usage of get_template_hierarchy() in wordpress


Answers ( 1 )


    The get_template_hierarchy() function in WordPress is designed to retrieve the template hierarchy for a specific template slug. This function is particularly useful for theme developers or plugin authors who need to understand or manipulate the way WordPress selects templates for rendering different types of content.

    Function Definition:

    get_template_hierarchy( string $slug, boolean $is_custom = false, string $template_prefix = '' ): string[]


    • Purpose: This function fetches the hierarchy of templates that WordPress will consider for a given template slug. The hierarchy determines which template files WordPress will look for in the theme directory to render the specified type of content.
    • Note: It's important to include "index" as the last fallback template in the hierarchy. This is because WordPress always needs a default template to fall back to if none of the other templates are available.


    1. $slug (string, required): The template slug for which the hierarchy is to be retrieved. The slug represents a specific type of content or context in WordPress, like 'single', 'page', 'archive', etc.

    2. $is_custom (boolean, optional): This parameter indicates whether the template is a custom one or part of the standard WordPress template hierarchy. The default value is false, meaning it's considered part of the standard hierarchy.

    3. $template_prefix (string, optional): This is used to define a prefix for the template being created. It's useful for extracting the main template type. For example, in a template slug like 'taxonomy-books', 'taxonomy' is the main template type that can be extracted using this prefix. The default value is an empty string.

    Return Value:

    • string[] (array of strings): The function returns an array of strings, each representing a template file name that WordPress will look for in the theme directory, in the order of priority. The array starts with the most specific template and ends with the most general one ('index.php').

    Example Usage:

    // Example: Get template hierarchy for a single post of a custom post type 'book'
    $templates = get_template_hierarchy('single', false, 'book');
    // This might return an array like:
    // ['single-book.php', 'single.php', 'index.php']
    // Indicating that WordPress will first look for 'single-book.php', then 'single.php', and finally 'index.php'

    In this example, the function is used to retrieve the hierarchy of templates for a single post of a custom post type named 'book'. The returned array shows the order in which WordPress will search for the templates in the theme directory.

Leave an answer