Wordpress test if the custom taxonomy term is a child of another term

How can I check if a wordonomonomy / term page is a child of another term? For example, if I have a taxonomy for "portfolio categories" that is hierarchical. my top-level terms are digital and print. under print, I have "television" .. and several others. if I am in the "television" archive, is_tax () is true, like is_tax ("television"), but not is_tax ('print'). in principle, I would like the โ€œtelevisionโ€ and its brothers and sisters to behave in one direction, while the children of the โ€œdigitalโ€ behave differently.

Is this possible or will it best serve individual taxonomies?

+3
source share
3 answers

On this page, say archive-portfolio-categories.php or just archive.php. I suppose you can use the global variable $ term to determine if you are on a child page. For instance:.

<?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..
}
?>
+6
source

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

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

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

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

, 2 "" "" . .

$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;

Please note that I changed the code to my own working code. There may be small typos. Therefore, please check and do not blindly copy this.

0
source

All Articles