Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress test if custom taxonomy term is child of another term

how can i test if a wordpress taxonomy/term page is a child of another term? For instance, if i have a taxonomy for "portfolio-categories" which is hierarchical. my top level terms are "digital" and "print". under print, i have "television".. and a few others. if i am on the "television" archive, is_tax() is true as is is_tax('television') but not is_tax('print'). basically i'd like 'television' and its siblings to behave one way while the children of "digital" behave another.

is this possible or would this be best served by separate taxonomies?

like image 400
helgatheviking Avatar asked Dec 27 '22 19:12

helgatheviking


2 Answers

In that page say archive-portfolio-categories.php or just archive.php .. I believe you can use the global variable $term to determine if you are on a child page. E.g.:

<?php 
$term = get_term_by( 'slug', get_query_var( 'term' ) );
if($term->parent > 0) 
{ 
// THIS IS A CHILD PAGE 
// .. DO STUFF HERE.. 
} 
else 
{ 
// THIS IS THE PARENT PAGE
// .. DO OTHER STUFF HERE..
}
?>
like image 63
Rich Telford Avatar answered Apr 08 '23 17:04

Rich Telford


This should work if you only have the 2 top-level items with slugs 'print' and 'digital'. This code will also work for deeper taxonomy trees.

$current_tax = wp_get_post_terms( $post->ID, 'portfolio-categories', array() );
$current_tax_id = $curcat[0]->term_id;

$digital = get_term_by( 'slug', 'digital', 'portfolio-categories', OBJECT );
$print = get_term_by( 'slug', 'print', 'portfolio-categories', OBJECT );

$sub_digital = get_term_children( $digital->term_id, 'portfolio-categories' );
$sub_print = get_term_children( $print->term_id, 'portfolio-categories' );

// this variable will hold the current top-level taxonomy term ID.
$parent_cat_id = in_array($current_tax_id, $sub_digital) ? $digital->term_id : $print->term_id;

Note that I have changed to code from my own working code. There might be small typo's. So please check and don't blindly copy paste this.

like image 37
Jules Colle Avatar answered Apr 08 '23 17:04

Jules Colle