How would I use the same template file for, say three specific taxonomy terms but not the remaining three?
I know taxonomy-taxname.php
is the file for all terms
I know taxonomy-taxname-termname.php
is the file for a specific term.
But let's say I want to have...
--taxonomy-fruit-redfruit.php
for strawberries, tomatoes and raspberries
--taxonomy-fruit-greenfruit.php
for watermelons, apples and kiwi
... without resorting to using duplicated individual theme files for each term?
How would I use the same template file for, say three specific taxonomy terms but not the remaining three?
I know taxonomy-taxname.php
is the file for all terms
I know taxonomy-taxname-termname.php
is the file for a specific term.
But let's say I want to have...
--taxonomy-fruit-redfruit.php
for strawberries, tomatoes and raspberries
--taxonomy-fruit-greenfruit.php
for watermelons, apples and kiwi
... without resorting to using duplicated individual theme files for each term?
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;
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
.