Get the id of a WooCommerce category, by name

天涯浪子 提交于 2020-02-03 08:52:27

问题


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?


回答1:


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 category slug…




回答2:


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);


来源:https://stackoverflow.com/questions/37504562/get-the-id-of-a-woocommerce-category-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!