0
votes

I am trying to create custom dynamic menu for Woocommerce, and it seem I am stuck. To mark my categories as active, I need category ID of a page that I am in at the moment.

If I am in a category I get id like this:

  if (is_product_category()) {
      global $wp_query;
      $curent_Cat_ID = $wp_query->get_queried_object()->term_id;
  } 

But it wont show anything on a product page. Is there a way to get category id on a product page? What I was able to find wasn't working anymore. Or somehow get an array like breadcrumbs with IDs?

1
On single product pages, use global $product; and $term_ids = $product->get_category_ids(); which gives an array of product category terms Ids. Or you can even use $terms_ids = wp_get_post_terms( get_the_ID(), 'product_cat', array( 'fields' => 'ids' ) );LoicTheAztec
Nope not working for accordion menu. If product have lets just say 5 categories all will be marked as active. and expanded.Donce

1 Answers

0
votes

Ok a good night sleep and eventually I found the answer. If someone will need it here it is:

       if ( is_tax( 'product_cat' ) ) {
            $current_cat   = get_queried_object_id();
            $cat_ancestors = get_ancestors( $current_cat, 'product_cat' );

        } elseif ( is_singular( 'product' ) ) {
            $terms = wc_get_product_terms(
                get_queried_object_id(),
                'product_cat',
                apply_filters(
                    'woocommerce_product_categories_widget_product_terms_args',
                    array(
                        'orderby' => 'parent',
                        'order'   => 'DESC',
                    )
                )
            );

            if ( $terms ) {
                $main_term     = apply_filters( 'woocommerce_product_categories_widget_main_term', $terms[0], $terms );
                $current_cat   = $main_term->term_id;
                $cat_ancestors = get_ancestors( $main_term->term_id, 'product_cat' );
            }
        }