Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the id of a WooCommerce product category by its slug

I have a wp template that I would like to assign to some pages. The template would ie. display all WooCommerce products that have the same master category name as the pages name itself.

By far I have tried using this code, but with no good output:

$idObj = get_category_by_slug($pagename);
$id = $idObj->term_id;
echo ": ". $id;

Unfortunately, the echo does not display anything.
Echoing $pagename works, and returns me the slug of the page.

Any good way I could make this work?

like image 543
aln447 Avatar asked May 28 '16 23:05

aln447


People also ask

How do I find the category ID of a slug?

Quick WordPress snippet for getting the category ID from the category slug. $slug = 'docs'; $cat = get_category_by_slug($slug); $catID = $cat->term_id; Here we pass the $slug to WordPress' get_category_by_slug() function.

How do I find category ID?

Simply open a category to edit, and you'll see the category ID in the browser's address bar. It is the same URL that appeared when there was a mouse hover on your category title. It means that the category ID is the number between 'category&tag_ID=' and '&post_type', which is 2.

How do I get a product slug in WooCommerce?

Go to WooCommerce > Settings > Custom Permalinks. 3. In the “product permalinks” section choose “Product slug alone” or “Product slug with category name” if you want to include category slug into URL.


1 Answers

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
like image 100
LoicTheAztec Avatar answered Nov 12 '22 16:11

LoicTheAztec