Display the child category of a specific parent category inside a product archive?

I have created a parent category named “brands” – the ID of that category is “10”.

Inside it I have added child categories like “Nike” “Adidas” etc.

Read More

Inside my product archive, I wish to show the names of the child category
associated ONLY with the parent category “brands” (ID 10).

For example: If a product is associated with “Nike” (who is a child of “brands” – it will show “Nike”. if not- show nothing.

I have tried the flowing but nothings works for me:

<?php 
$categories = get_the_terms( get_the_ID(), '10' ); 
if ( $categories && ! is_wp_error( $category ) ) : 
    foreach($categories as $category) :
      $children = get_categories( array ('taxonomy' => '10', 'parent' => $category->term_id ));

      if ( count($children) == 0 ) {
          echo $category->name;
      }
    endforeach;
endif;
?>

And:

<?php
$categories = get_the_terms( get_the_ID(), '10' ); 
if ( $categories && ! is_wp_error( $category ) ) : 
    foreach($categories as $category) :
      $children = get_categories( array ('taxonomy' => '10', 'parent' => $category->term_id ));
      if ( count($children) == 0 ) { ?>
      <span class="product-sub-cats"><?php echo $category->name; ?></span>
      <?php }
    endforeach;
endif; ?>

And also:

<?php 
if($termid->parent > 10) {
    $args = array(
        'orderby'       => 'name', 
        'order'         => 'ASC',
        'hide_empty'    => false, 
        'child_of'      => $termid->parent,
    ); 

$categories = get_the_terms( get_the_ID(), 'product_cat', $args ); 
if ( $categories && ! is_wp_error( $category ) ) : 
    foreach($categories as $category) :
      $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
      if ( count($children) == 0 ) { ?>
      <span class="product-sub-cats"><?php echo $category->name; ?></span>
      <?php }
    endforeach;
endif;
}
?>

Related posts

Leave a Reply

1 comment

  1. I have found a solution for this issue.

    In order to achieve this, you need to use:
    https://codex.wordpress.org/Function_Reference/wp_get_post_terms

    This is the code that is working for me:

    <?php
    global $post;
    $brands_id = get_term_by('slug', 'PARENT-CAT-SLUG', 'product_cat');
    
    $terms = get_the_terms($post->ID, 'product_cat');
    foreach ($terms as $term) {
        if($term->parent === $brands_id->term_id) { ?>
           <span class="product-sub-cats"><?php echo $term->name; ?></span>
          <?php  break;
        }
    }
     ?>