1

I'm looking to determine if a taxonomy term has children. See the below markup and I'll explain what I mean:

<?php
$terms = get_terms("wpsc_product_category");
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
    foreach( get_terms( 'wpsc_product_category', array( 'hide_empty' => false, 'parent' => 0 ) ) as $parent_term ) { ?>
    <li class="header-menu-item" data-hook="<?php echo $parent_term->slug; ?>">
        <a href="<?php echo home_url(); ?>/products/<?php echo $parent_term->slug; ?>"><?php echo $parent_term->name; ?></a>                
    </li>
    <?php }
} ?>

So this outputs a list of all parent taxonomy terms for the wpsc_product_category taxonomy, but I want to determine if the taxonomy term has children or not, and if so add the parent class to the relevant header-menu-item so I can attach a jquery function to it. I'm not sure if this is possible? Any suggestions would be greatly appreciated!

2 Answers 2

4

The get_term_children function should help here.

This returns an array, either with the child terms inside it, or empty. Checking if this array is truthy or not as you loop through will then let you determine whether or not to add the class.

<?php
    $terms = get_terms('wpsc_product_category');
    if ( !empty( $terms ) && !is_wp_error( $terms ) ){
    foreach( get_terms( 'wpsc_product_category', array( 'hide_empty' => false, 'parent' => 0 ) ) as $parent_term ) {
        $term_children = get_term_children($parent_term->term_id, 'wpsc_product_category'); ?>
        <li class="header-menu-item<?php echo ($term_children ? ' parent' : ''); ?>" data-hook="<?php echo $parent_term->slug; ?>">
            <a href="<?php echo home_url(); ?>/products/<?php echo $parent_term->slug; ?>"><?php echo $parent_term->name; ?></a>                
        </li>
    <?php }
} ?>
2
  • Thanks for your suggestion, doesn't seem to work though? I've implemented the code, to no effect as the parent class isn't being added? Nov 18, 2014 at 13:32
  • @PieterGoosen voila! That edit has fixed it, worked a charm :) Nov 18, 2014 at 13:37
1

You might try leveraging get_term_children to generate an array of all the children of that taxonomy, and then check against empty().

Since it returns an empty array, you should be able to do something like this:

(You'll need to find out your term's id, which is a number, and replace it in the below $term_id variable)

$term_id = 2
$taxonomy_name = 'wpsc_product_category';
$terms = get_term_children( $term_id, $taxonomy_name );

if ( !empty( $terms ) && !is_wp_error( $terms ) ){
 // do your stuff
}

Your Answer

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

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