0

To be more precise I'm trying to get the category name as a class.

I want it under the title, so something like:

echo '<h3><a href="' . get_the_permalink() . '">' . get_the_title() . '</a>
</h3>';
echo '<span style="display:none;" class="prodcat';
$categories = array( Category1, Category2);
foreach ($categories as $category) {
echo ' ' . $category . '';
};
echo '"> </span>';

I just can't figure out how to get he categories from the product to replace "array( Category1, Category2);"

I've messed around a whole lot, the closest I've gotten is displaying "Array"

  • I didn't understand your issue, are you not getting categories, or getting categories but not able to print name properly? – Aniruddha Gawade Jun 16 '17 at 5:22
0

Product categories in Woocommerce is a term, so you can get the categories with get_the_terms function:

echo '<h3><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h3>';
echo '<span style="display:none;" class="prodcat';
$categories = get_the_terms( get_the_ID(), 'product_cat' );
foreach ($categories as $category) {
    echo ' ' . $category->name . '';
};
echo '"> </span>';
  • Thanks dbeja. Easy when you know how! Do you know how I would echo the parent category? – Barton Keyes Jun 16 '17 at 13:58
  • You can use: $parent = get_category($category->parent); and then just echo $parent->name. Also be aware that if $category->parent is 0 (it can have no parent) it will probably throw an error, so it would be good to check for that. – dbeja Jun 16 '17 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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