通过子句获取WooCommerce产品类别的ID [英] Get the id of a WooCommerce product category by its slug

查看:61
本文介绍了通过子句获取WooCommerce产品类别的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个wp模板,我想分配给某些页面.该模板即.显示所有具有与页面名称本身相同的主类别名称的WooCommerce产品.

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;

不幸的是,回声未显示任何内容.
回显 $ pagename 可行,并向我返回该页面的信息.

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?

推荐答案

建议使用自定义分类法,而不要使用 get_term_by():

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

参考:从词条中获取类别ID ...

要从术语名称中获取产品类别ID,请使用:

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

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

这篇关于通过子句获取WooCommerce产品类别的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆