4
votes

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?

3

3 Answers

8
votes

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..
}
?>
1
votes

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.

1
votes

The global $term not appear. But you can use the global $wp_query, you can test in taxonomy-{tax}.php :

<?php
global $wp_query;
var_dump($wp_query);
?>

We see the $wp_query->queried_object->parent, and :

<?php
global $wp_query;
var_dump($wp_query);
if($wp_query->queried_object->parent == '0' && is_tax()){
    //parent
}else {
    //child
}
?>