woocommerce - How do I get the most top level category of the current product category

Viewed 49466

I have a Woocommerce product and I need to display on that page the Most top level category of a category assigned to the product

- Main Product Category
-- Sub Product Category
--- Category Assigned to product

I need to get the ID or name of "Main Product Category" so that I can display it in the single product category.

I already tried doing the following:

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

foreach ($terms as $term) {
$product_cat_id = $term->term_id;

$thetop_parent = woocommerce_get_term_top_most_parent( $product_cat_id , 'product_cat' );

echo $thetop_parent;
}

But It didn't worked at all and it brakes the page from loading after woocomerce_get_term... I'm not sure what to do at this point It

thanks for any help on this.

7 Answers

For those looking for a clean solution, I've extended @Nicolas GRILLET's function so that you only need to pass in a product ID and you get the term ID, Name and Link (URL).

function get_parent_terms(int $product_id)
{
    // Get all the terms associated with the product
    $product_terms = get_the_terms($product_id, 'product_cat');

    // Check if there are terms associated with the product
    if ($product_terms) {

        // Loop through $product_terms to find parent terms
        foreach ($product_terms as $product_term) {

            // Climb up the taxonomy hierarchy until parent found
            while ($product_term->parent > 0) {
                $product_term = get_term_by("id", $product_term->parent, "product_cat");
            }

            // Store parent terms as objects in array $parent_terms
            $parent_terms[] = (object)[
                'term_id' => $product_term->term_id,
                'name' => $product_term->name,
                'link' => get_term_link($product_term->term_id, 'product_cat')
            ];
        }

        // Return array of parent terms
        return $parent_terms;
    } else {
        // Return false if there are no terms 
        return false;
    }
}

This will give you an array of all the top-level categories a product belongs to.

Assuming your products only have one top-level category then the example below shows how to get the product's top-level category id, name and link.

// Get the first top level category (object)
$top_level_cat = get_parent_terms($product_id)[0];

// Echo the ID
echo $top_level_cat->term_id;

// Echo the Name
echo $top_level_cat->name;

// Echo the Link/URL
echo $top_level_cat->link;

Use this to get the Top Parent Category:

$uncategorized_term_id = get_option( 'default_product_cat' );
Related