Custom Template for more than 1 Tag

WordPress let me create custom tag templates, i have lots of tags, and i want to display the post tagged with some tags with a template, and the post tagged with other tags with another template.
enter image description here

As this image shows the template hierarchy let me create the tag template easily, giving to the page the name or the id of the tag.
But i want to create 1 template tag for a great number of tags (instead of making 1 template for every different tag), and another template tag for the remaining one.

Related posts

Leave a Reply

2 comments

  1. Here’s an example that “abuses” the tag description field to store a template name for the tag. We use the tag_template filter to get the tag description if it exists and include a template file with the description as part of the name. You could extend this to whitelist specific template names so typos don’t result in trying to load a file that doesn’t exist:

    function wpd_tag_template( $templates = '' ){
        $tag = get_queried_object();
        if( !empty( $tag->description ) ){
            $templates = locate_template( 'custom-tag-' . $tag->description . '.php', false );
        }
        return $templates;
    }
    add_filter( 'tag_template', 'wpd_tag_template' );
    

    So for example the description contains template-1, WordPress will load the file custom-tag-template-1.php for this tag.

  2. You can use tag.php for the great number of tags and use tag-{slug}.php for remaining ones.

    Also, you can use conditional tags for all in one file, tag.php:

    if ( is_tag( '{tag-one}' ) ) {
      // only for tag with slug "tag-one"
    } elseif ( is_tag( '{tag two}' ) ) {
      // only for tag with slug "tag-two"
    } elseif ( is_tag( '{tag three}' ) ) {
      // only for tag with slug "tag-three"
    } else {
      // Load default view for a great number of tags
    }
    

    Even, is_tag() accepts an array of slugs or ids.

    I hope I get it right.