Get the id of a WooCommerce product category by its slug Get the id of a WooCommerce product category by its slug wordpress wordpress

Get the id of a WooCommerce product category by its slug


With a custom taxonomy is recommended to use get_term_by() instead :

$category = get_term_by( 'slug', $pagename, 'product_cat' );$cat_id = $category->term_id

Reference: Get category ID from term slug…


To get a product category ID from term name, use:

$category = get_term_by( 'name', $pagename, 'product_cat' );$cat_id = $category->term_id


The code seems to be correct, try a var_dump to see what you are getting from get_category_by_slug($pagename)

$idObj = get_category_by_slug($pagename);var_dump($idObj);