Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Can someone please help me, I'm looking for a way to find the main parent product category of a WooCommerce product? Say, the product is marked under Gadgets, but the main parent of them all is Electronics.

I want this per post, as I want to add a class to each post signifying its main parent product_cat.

Please remember, product categories are custom taxonomy, and cannot be retrieved using get_category_parents(). They are listed as terms.

Thanks in advance.

// edit:

This is the code I have already, I'm calling this on each post and my posts are rendered similar to an archive page.

function all_cat_classes($post) {
    $cats = "";

    $terms = get_the_terms($post->ID, "product_cat");

    $count = 0;
    $count = count($terms);
    $key = 0;
    foreach ($terms as $cat) {

        $key++;
    }

    return $cats;
}
share|improve this question

2 Answers

You can try this:

<?php
  $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
  $parents = get_the_terms($term->parent, get_query_var('taxonomy') );

  foreach( $parents as $parent ) {
    echo $parent->name;
  }

?>
share|improve this answer
How would you handle more than two levels of categories? – Anriëtte Myburgh Jun 28 '12 at 9:38
up vote 0 down vote accepted

I wrote my own function to go all the way up the "chain". My recursive might not be the best implementation you've seen, but it works.

function get_parent_terms($term) {
    if ($term->parent > 0) {
        $term = get_term_by("id", $term->parent, "product_cat");
        if ($term->parent > 0) {
            get_parent_terms($term);
        } else return $term;
    }
    else return $term;
}

# Will return all categories of a product, including parent categories
function all_cat_classes($post) {
    $cats = ""; 
    $terms = get_the_terms($post->ID, "product_cat");
    $key = 0;

    // foreach product_cat get main top product_cat
    foreach ($terms as $cat) {
        $cat = get_parent_terms($cat);
        $cats .= (strpos($cats, $cat->slug) === false ? $cat->slug." " : "");
        $key++;
    }

    return $cats;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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