0

I want to get the current category for my WooCommerce products and display it beneath my products. Currently it gets the category by alphabetical order. This is a little odd when you have a parent category called "clearance" and a child category called "shoes" and it gets the clearance one instead even when going to the shoes category.

The function that is built into the theme right now is posted below.

function gbx_wc_get_cat_forproduct() {
global $smof_data, $product;

if (!$smof_data['show_shop_category'])
    return;

$terms = get_the_terms($product->ID, 'product_cat');
if ($terms && !is_wp_error($terms)) {
    foreach ($terms as $term) {
        echo '<a class="product-cat" href="' . get_term_link($term->slug, 'product_cat') . '">' . $term->name . '</a>';
        break;
    }
}
}

I googled how to do this but my PHP knowledge is limited to say the least. I also seen another question but it didn't seem to help me. --- WooCommerce - get category for product page

Example of issue

Community
  • 1
  • 1
Anthony Russo
  • 913
  • 4
  • 13
  • 31
  • By current category, you mean that this is displaying on a product category page, correct? And it's listing the parent category, but you'd like it to ignore that parent category in favor of... the current category page's name? – Cameron Hurd Apr 04 '14 at 16:37
  • No. I added an example photo of the issue. – Anthony Russo Apr 05 '14 at 01:10
  • I realise this is an older question, but it's because the shoes you're seeing are probably in both categories (shoes and clearance), and your code above only shows the first category in the returned category list, due to the "break;" in the foreach loop. – flauntster Jun 28 '15 at 10:32
  • 2
    Additionally you could look into using $product->get_categories(); which returns a string of categories a product belongs to. – flauntster Jun 28 '15 at 10:33
  • That is what I ended up doing. – Anthony Russo Jul 12 '15 at 20:09

0 Answers0