17

How do I get the current product category that the user is browsing through?

I am trying to use get_the_terms($post->ID, 'product_cat'); but this is giving me the categories for each product listed on the page. I would like to get the current category user is browsing through, the current product listing page.

Caio Mar
  • 2,344
  • 5
  • 31
  • 37

4 Answers4

24

Here is a one liner:

$wp_query->get_queried_object()->term_id;

or

$wp_query->get_queried_object()->name;

or

...
Etienne Dupuis
  • 13,548
  • 6
  • 47
  • 58
  • 1
    Great, this works for both product and post categories and terms. – JMRC May 16 '17 at 19:27
  • 3
    `print_r( $wp_query->get_queried_object() );` to see all the available indexes -- not just `term_id`. example: `echo $wp_query->get_queried_object()->name;` – aequalsb Aug 09 '17 at 04:44
14

To get the current category ID. you have to use

get_queried_object();

The proper way for doing this is..

$cate = get_queried_object();
$cateID = $cate->term_id;
echo $cateID;
  • Can't believe how much time I spent searching for this simple answer. WooCommerce is deceivingly similar to vanilla WordPress. Until it isn't. – Fred Rocha Nov 18 '22 at 11:47
11

try this :

        global $post;
        $terms = get_the_terms( $post->ID, 'product_cat' );
        $nterms = get_the_terms( $post->ID, 'product_tag'  );
        foreach ($terms  as $term  ) {
            $product_cat_id = $term->term_id;
            $product_cat_name = $term->name;
            break;
        }

       echo $product_cat_name;
Ravimallya
  • 6,550
  • 2
  • 41
  • 75
hafizuddin
  • 111
  • 1
  • 3
0

By the way, you can create shortcode [show_product_category_id], that will show product's category id. For example, while browsing a category of products, it will show this id. You can open functions.php of the theme and add this:

add_shortcode( 'show_product_category_id', 'show_product_category_id' );

function show_product_category_id() {
$cat = get_queried_object();
$catID = $cat->term_id;
echo $catID;
}
Krechet USA
  • 15
  • 1
  • 3