1

I made the below for my sidebar to show the subcategories of a specific category (ID 89) of my choosing. Only the subcategories that the post is in appear. Works great.

Now I want to change my posts in to WooCommerce Products, so I'm trying to adapt the code to target WC subcategories instead of post categories. I'm a bit lost on where to start.

<ul>
    <?php foreach (get_the_category() as $childcat) : ?>
    <?php if (cat_is_ancestor_of(89, $childcat)) { ?>
        <li>
            <a href="<?php echo get_category_link($childcat->term_id); ?>"><?php echo $childcat->cat_name; ?></a>
        </li>
    <?php } ?>
    <?php endforeach; ?>
</ul>
1

...to show the subcategories of a specific category (ID 89) ...

Try this

$product_cats = wp_get_post_terms( $post->ID, 'product_cat' );
if ( ! empty( $product_cats ) && ! is_wp_error( $product_cats ) ) { ?>
<ul>
    <?php 
    foreach ($product_cats as $childcat) : ?>
    <?php if ($childcat->parent == 89)) { ?>
        <li>
            <a href="<?php echo get_term_link($childcat->term_id); ?>"><?php echo $childcat->name; ?></a>
        </li>
    <?php } ?>
    <?php endforeach; ?>
</ul>
<?php } ?>

I hope this helps.

  • Hmmm, the second line is breaking my site. But I see where this is going now; I'm going to tinker with it. Thanks !! – SeanAUS120 Mar 30 at 0:12
  • @SeanAUS120 Answer updated. There was a missing } after </ul> at the end of code which I forgot to format as part of code block and consequentle WPSE did not rendered it. – Qaisar Feroz Mar 30 at 4:14

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.