Woocommerce How to get First Level product category?

I have a url like this on my shop page: /product-category/footwear/nike-sb/, but when I run this code here:

$cat = $wp_query->get_queried_object();

Read More

it returns the object for nike-sb, I need the object for footwear returned at all times. If I go here in my browser: /product-category/footwear/ it returns the object for footwear just fine. But how to get the object for footwear at all times, if we are in the footwear, first-level, category?

So, for example, if we are at the url /product-category/shirts/hanes/, it should return the shirts object instead.

Using WooCommerce for this, but unable to get a grip on the category directly after product-category within the url. Seems to only return the latest category components.

How to do this?

Related posts

Leave a Reply

1 comment

  1. This is a question I’ve had to solve and I published it here

    One caveat: I did find a bug with this that I haven’t had time to solve yet, and that bug is when you pass a product ID that is at a top level category already. For whatever reason it doesn’t come back correctly.

    This is a helper function and should be used by other functions that call their own actions/hooks to be run.

    function get_product_top_level_category ( $product_id ) {
    
                    $product_terms            =  get_the_terms ( $product_id['product_id'], 'product_cat' );
                    $product_category         =  $product_terms[0]->parent;
                    $product_category_term    =  get_term ( $product_category, 'product_cat' );
                    $product_category_parent  =  $product_category_term->parent;
                    $product_top_category     =  $product_category_term->term_id;
    
                    while ( $product_category_parent  !=  0 ) {
                            $product_category_term    =  get_term ( $product_category_parent, 'product_cat' );
                            $product_category_parent  =  $product_category_term->parent;
                            $product_top_category     =  $product_category_term->term_id;
                    }
    
                    return $product_top_category;
    
            }