最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

categories - List subcategories of a specific product category (adapting from posts to products taxonomy)

matteradmin9PV0评论

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>

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>
Share Improve this question asked Mar 17, 2019 at 19:05 SeanAUS120SeanAUS120 311 silver badge4 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

Post a comment

comment list (0)

  1. No comments so far