-1

I was wondering if someone could give me a hand. I would like to display the child categories of my woo commerce store categories along with the thumbnails I have set for them in my dashboard. I have set up two parent categories "Men" "Women". Under these two parents I have a few categories for each as children. From what I understand the woo commerce categories are formulated through a custom taxonomy. So I did not use get_the_category() instead I used get_terms(). I have used the code below, The thumbnails and the perma links work for each term but this code is still displaying the parent terms. Could someone please tell me what I am doing wrong here? I really appreciate the help!

<?php

    $taxonomyName = "product_cat";
    $prod_categories = get_terms($taxonomyName, array(
            'orderby'=> 'name',
            'order' => 'ASC',
            'hide_empty' => 1
    ));  

    foreach( $prod_categories as $prod_cat ) :
            $terms = get_terms($taxonomyName, array('parent' => $prod_cat->term_id, 'orderby' => 'slug', 'hide_empty' => false));
            $cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
            $cat_thumb_url = wp_get_attachment_thumb_url( $cat_thumb_id );
            $term_link = get_term_link( $prod_cat, 'product_cat' );
    ?>

    <li><a href="<?php echo $term_link; ?>"><img src="<?php echo $cat_thumb_url; ?>" alt="<?php echo $prod_cat->name; ?>" /></a></li>
    <?php endforeach; wp_reset_query(); ?>
  • @PieterGoosen I have restructured the function and have given more information about the question. THANK YOU! – steamfunk Jun 17 '15 at 16:46
1

I'm not completely sure that you do actually need get_terms() twice. It looks very ineffecient and overboard. I don't know if you need this for ordering purposes, but still, there are better ways of doing this without hitting the db so hard. One alternative is to make one call to get_terms() and then use usort() to sort your terms by parent. But this is beyond what your question is about.

There are a couple of ways to exclude the parent terms

  • Simply use the exclude parameter in get_terms() to exclude the parent categories. If your parents have id's 1 and 2, then you would add 'exclude' => [1, 2], to your arguments in get_terms()· (Note, the new short array syntax is only available from PHP 5.4. For older versions use 'exclude' => array( 1, 2 ),)

  • You can also just loop over the parents. If your parents are top level terms, then their parent id will be 0, so you can simply add the following in your foreach loop

    if ( $prod_cat->parent == 0 )
        continue;
    

    Alternatively, you can use their respective ids to skip them

    if ( $prod_cat->term_id == 1 || $prod_cat->term_id == 2 )
        continue;
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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