How to use same theme template for multiple taxonomy terms?

You prepare templates (staying with your example):

  • content-redfruits.php,
  • content-greenfruits.php,
  • content-fruits.php.

Then in taxonomy file taxonomy-fruit.php (copy and rename taxonomy.php or index.php), before main loop check the term slug of the currently-queried object.

$red_templ = ['strawberries', 'tomatoes', 'raspberries']; // term slugs
$green_templ = ['watermelons', 'apples', 'kiwi'];         // term slugs
$template="fruits";

$obj = get_queried_object();
if ( $obj instanceof WP_Term ){
    if ( in_array($obj->slug, $red_templ) )
        $template="redfruits";
    else if ( in_array($obj->slug, $green_templ) )
        $template="greenfruits";
}
while ( have_posts() ) : the_post();

    get_template_part( 'content', $template );

endwhile;

Edit: (answer to the comment)

The above example can be written using is_tax:

$red_templ = ['strawberries', 'tomatoes', 'raspberries']; // term slugs
$green_templ = ['watermelons', 'apples', 'kiwi'];         // term slugs
$template="fruits";

if ( is_tax('fruit', $red_templ) )        // check taxonomy, then check terms
    $template="redfruits";
else if ( is_tax('fruit', $green_templ) ) // check taxonomy, then check terms
    $template="greenfruits";

while ( have_posts() ) : the_post();

    get_template_part( 'content', $template );

endwhile;

is_tax performs some additional comparisons, but here is no significant difference in performance.
Each time you call is_tax, you check if given taxonomy matches the current one (this has already been checked when choosing a template file) and compare terms by id, slug and name.

You do not want to use has_term in this case. This function works on a post, therefore for empty terms it will return falsely false.

Leave a Comment