0

Hi basically I have categori ID number (134) that has 2 child of that (red and blue). I selected the blue one. I want to display only the selected one (blue). But at the moment the show all subcategories (red and blue). Please help me here my code

$args = array(
   'hierarchical' => 1,
   'show_option_none' => '',
   'hide_empty' => 0,
   'parent' => 134,
   '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>';

Here for single product page.

0

1 Answer 1

0

To display only assigned category you need to change hide_empty to true.

Please see the modified code:

$args = array(
 'hierarchical' => 1,
 'show_option_none' => '',
 'hide_empty' => true,
 'parent' => 134,
 '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>';

Please see the updated code:

$cats_list = get_the_terms ( get_the_ID() , 'product_cat' );

echo '<ul class="wooc_sclist">';
foreach ($cats_list as $cats) {
$link = get_term_link( $cats->slug, $cats->taxonomy );
echo '<li><a href="'. $link .'">'.$cats->name.'</a></li>';
}
echo '</ul>';
10
  • OMG you are right!! thank you so muchhh Jun 19, 2019 at 2:12
  • Hi sorry another problem, just realized it show all the subcategories which didn't selected in that product. can you please check this link? baliartsgallery.com/product/wonderful-dreamland-l1-painting Jun 19, 2019 at 16:03
  • @WildaSagita, Please try this code to get product's assigned categories: $terms = get_the_terms ( $product_id, 'product_cat' ); foreach ( $terms as $term ) { $cat_id = $term->id; }
    – Bhupen
    Jun 20, 2019 at 3:44
  • Hi sorry I'm very beginner, can you please explain me more for the full code? Jun 20, 2019 at 5:36
  • You want to display categories assigned to the product. Right?
    – Bhupen
    Jun 20, 2019 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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