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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With