How to get current category id in a template or theme functions file while using Woocommerce. In fact not only using Woocommerce but this method can be used to get the category object and subsequently the ID in normal category page.
[php]
global $wp_query;
// get the query object
$cat_obj = $wp_query->get_queried_object();
pr($cat_obj);
if($cat_obj) {
$category_name = $cat_obj->name;
$category_desc = $cat_obj->description;
$category_ID = $cat_obj->term_id;
}
[/php]
The debugging pr() function (abbreviation of print_r()) would print the category object something similar to the following:
[code]
stdClass Object
(
[term_id] => 19
[name] => Dairy Rations
[slug] => dairy
[term_group] => 0
[term_taxonomy_id] => 19
[taxonomy] => product_cat
[description] => Being a small boutique style mill we are able to custom manufacture a ration to your specific needs and requirements.
[parent] => 0
[count] => 3
)
[/code]
Hi i want to display parent category by his id and also display subcategories of that parent in woo comm…. please help
Thanks so much! Clear and concise.
I found a more “proper” way to do this. I am creating a WooCommerce site where people can filter by both category and custom taxonomies. The issue is, when I have a URI like such:
/product-category/rock-and-roll/?theme=edgy
… wordpress gives priority to the “theme” taxonomy, making the “queried_object” the taxonomy and not the product category. In order to get the product category, you can use something like the following:
global $wp_query;
$category_name = $wp_query->query_vars['product_cat'];
if( $category_name ) {
$category_object = get_term_by('name', $category_name, 'product_cat');
$category_id = $category_object->term_id;
}
Thanks! it’s working…
My Pleasure!
Helped me lot.. Thank you so much..
Hi
Good Job, this code save my couple of hrs.
Thanks
Aman