Using WordPress ‘get_tag_template()’ PHP function

The get_tag_template() WordPress PHP function retrieves the path of the tag template in the current or parent template.

Usage

$template_path = get_tag_template();

Parameters

  • None

More information

See WordPress Developer Resources: get_tag_template()

Examples

Display a custom tag template

In this example, we will create a custom tag template for a specific tag using the template_include filter.

// functions.php
function custom_tag_template($template) {
    if (is_tag('wordpress')) {
        return get_stylesheet_directory() . '/tag-wordpress.php';
    }
    return $template;
}
add_filter('template_include', 'custom_tag_template');

Check if the current template is a tag template

In this example, we will check if the current template being used is a tag template and display a message accordingly.

// header.php
if (get_tag_template() == get_query_template('tag')) {
    echo 'This is a tag template!';
}

Customize the tag template hierarchy

In this example, we will customize the tag template hierarchy by adding a new template file called custom-tag.php before the default tag.php.

// functions.php
function custom_tag_hierarchy($templates) {
    array_splice($templates, 2, 0, 'custom-tag.php');
    return $templates;
}
add_filter('tag_template_hierarchy', 'custom_tag_hierarchy');

Retrieve the tag template path and include a custom file

In this example, we will retrieve the path of the tag template and include a custom file.

// functions.php
function include_custom_file() {
    if (is_tag()) {
        $tag_template = get_tag_template();
        include_once(get_stylesheet_directory() . '/custom-file.php');
    }
}
add_action('wp_head', 'include_custom_file');

Modify the tag template path using the {$type}_template filter

In this example, we will modify the tag template path using the tag_template filter.

// functions.php
function change_tag_template_path($template) {
    if (is_tag('wordpress')) {
        return get_stylesheet_directory() . '/new-tag-wordpress.php';
    }
    return $template;
}
add_filter('tag_template', 'change_tag_template_path');