1

When tag-{slug}.php is in the root of theme, say wp-content/themes/p2/tag-{slug}.php, the template hierarchy is respected.

However, I have many such custom files and just cannot have it in the theme root directory . When I tested with p2/tag and p2/custom-tag directories, it did not work.

Any insight?

  • Without knowing exactly why you have many, or other details, one suggestion would be to look into using template parts. This would allow you to use one tag template file with some logic around various get_template_part statements: codex.wordpress.org/Function_Reference/get_template_part. Your many parts could reside in a folder that way. – jdm2112 Aug 3 '15 at 6:20
2

When you look at the source code, the tag template is loaded as follow in template hierarchy

So, moving your templates to a sub-folder will not work out-of-the-box. get_query_template() however have a filter (apply_filters( "{$type}_template", $template )) that we can use to change this behavior and load our tag-{$tag->slug}.php from a subfolder

So, we should do the following

  • Check if our tag-{$tag->slug}.php exists in our subfolder of choice

  • Load our tag-{$tag->slug}.php from subfolder if it exists

  • Load default templates from the hierarchy if tag-{$tag->slug}.php does not exists in a subfolder

Something like the following will work

add_filter( 'tag_template', function ( $template )
{
    $tag = get_queried_object();
    // Alternative path to desired template
    $alternative_template = locate_template( "custom-sub-folder/tag-{$tag->slug}.php" ); // Change subfolder name

    // If we do have "tag-{$tag->slug}.php" in a subfolder, load "subfolder/tag-{$tag->slug}.php"
    if (  $alternative_template )
        return $template = $alternative_template;

    // If we don't have a "tag-{$tag->slug}.php", load templates according to hierarchy
    return $template;
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.