Display all the subcategories from a specific category?

I need to show all subcategories using

$product_category = wp_get_post_terms( $post->ID, 'product_cat' );

actually I use:

Read More
<?php 

global $post;

$terms = get_the_terms( $post->ID, 'product_cat', 'hide_empty=0'  );
foreach ( $terms as $term ){
    $category_id = $term->term_id;
    $category_name = $term->name;
    $category_slug = $term->slug;

    echo '<li><a href="'. get_term_link($term->slug, 'product_cat') .'">'.$category_name.'</a></li>';
}   

?>

It’s ok but it shows only the parent category and only one subcategory…

How to fix that?

Related posts

2 comments

  1. Try something like this:

    by ID

    function woocommerce_subcats_from_parentcat_by_ID($parent_cat_ID) {
        $args = array(
           'hierarchical' => 1,
           'show_option_none' => '',
           'hide_empty' => 0,
           'parent' => $parent_cat_ID,
           'taxonomy' => 'product_cat'
        );
      $subcats = get_categories($args);
        echo '<ul class="wooc_sclist">';
          foreach ($subcats as $sc) {
            $link = get_term_link( $sc->slug, $sc->taxonomy );
              echo '<li><a href="'. $link .'">'.$sc->name.'</a></li>';
          }
        echo '</ul>';
    }
    

    by NAME

    function woocommerce_subcats_from_parentcat_by_NAME($parent_cat_NAME) {
      $IDbyNAME = get_term_by('name', $parent_cat_NAME, 'product_cat');
      $product_cat_ID = $IDbyNAME->term_id;
        $args = array(
           'hierarchical' => 1,
           'show_option_none' => '',
           'hide_empty' => 0,
           'parent' => $product_cat_ID,
           'taxonomy' => 'product_cat'
        );
      $subcats = get_categories($args);
        echo '<ul class="wooc_sclist">';
          foreach ($subcats as $sc) {
            $link = get_term_link( $sc->slug, $sc->taxonomy );
              echo '<li><a href="'. $link .'">'.$sc->name.'</a></li>';
          }
        echo '</ul>';
    }
    

    Source/inspiration

    Edit:

    Completed the code, tested it, see comments

  2. Here is the code that worked for me in a page template (my parent id was 7):

    <?php $wcatTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC', 'parent' => 7, )); 
            foreach($wcatTerms as $wcatTerm) : 
            $wthumbnail_id = get_woocommerce_term_meta( $wcatTerm->term_id, 'thumbnail_id', true );
            $wimage = wp_get_attachment_url( $wthumbnail_id );
        ?>
        <div><a href="<?php echo get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ); ?>">
        <?php if($wimage!=""):?><img src="<?php echo $wimage?>" class="aligncenter"><?php endif;?></a>
        <h3 class="text-center"><a href="<?php echo get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ); ?>"><?php echo $wcatTerm->name; ?></a></h3>
        </div>
        <?php endforeach; ?> 
    

Comments are closed.