1

I have a taxonomy called region with a hierarchical structure;

• Southern Africa
  • Botswana
  • South Africa
  • Zambia
  • Zimbabwe

In my taxonomy-region.php template file I would like to list the child terms when on Southern Africa (parent) and show nothing when on Botswana (child).

I have the following code where I'd like it to display:

<?php 
$current_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' )); ?>
<h5>Countries</h5>
<?php $cats = wp_list_categories( array(
    'parent' => $current_term->term_id,
    'taxonomy' => $current_term->taxonomy,
    'hide_empty' => 0,
    'hierarchical' => true,
    'depth' => 2,
    'title_li' => ''
    )); 
?>
<ul>
  <?php foreach ((array)$cats as $cat) {
    echo '<li><a href="'. get_category_link($cat).'" title="'. $cat->$cat_name .'">' . $cat->cat_name . '</a></li>'; }
  ?>
</ul>

Any help would be appreciated.

1 Answer 1

1

For reliability, you can get the current term being viewed from the queried object from $GLOBALS['wp_the_query']

$current_term = sanitize_term( $GLOBALS['wp_the_query']->get_queried_object() );

To answer your question, if Southern Africa is top level, it should have a parent term ID of 0. All child terms should have a numeric value as parent which corresponds to the parent term id they belong to.

With this in mind, you can simply check the value of $current_term->parent, and if the value is not 0, hide your code

$current_term = sanitize_term( $GLOBALS['wp_the_query']->get_queried_object() );
if ( 0 == $current_term->parent ) {
    // This is a top level page, show our code

        // ADD YOUR CODE HERE

}

Just another tip, I would use get_terms() for my list

3
  • Sorry, please recheck, had a slight error in my code Commented Jun 22, 2016 at 8:39
  • Thanks @PieterGoosen, it works perfectly. Just one question; do you mean you would use get_terms() in place of wp_list_categories()? Would I need to alter the array in that case? Commented Jun 22, 2016 at 12:42
  • Great, glad it worked for you. Personally yes, I would tend to use get_terms(), it is a bit faster, but anyways, it really isn't a trainsmash, we are talking ms here. You would need to change one or two parameters though if you want to go the get_terms() route. You should go and check out the codex on get_terms and play around with it. . Commented Jun 22, 2016 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.