如何解决获取WooCommerce中当前产品类别的兄弟姐妹术语ID的列表
我想根据当前类别ID检索术语ID列表。
此刻我正在使用以下代码:
$product_cat_items = get_queried_object();
$product_cat_id = $product_cat_items->term_id;
$product_cat_child = get_term($product_cat_id,'product_cat');
$product_cat_parent = $product_cat_child->parent;
$product_cat_related= get_terms('product_cat',array( 'parent' => $product_cat_parent,'exclude' => $product_cat_id ));
它正在运行,我得到了一系列的术语。 但是探查性的是,我只需要来自term对象的ID即可获得这样的列表:
123,345,678
有什么方法可以从$product_cat_related
数组中提取这样的列表吗?
这是当前输出:
array(2) {
[0]=>
object(WP_Term)#26238 (10) {
["term_id"]=>
int(177)
["name"]=>
string(27) "Name"
["slug"]=>
string(21) "name"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(177)
["taxonomy"]=>
string(11) "product_cat"
["description"]=>
string(0) ""
["parent"]=>
int(140)
["count"]=>
int(8)
["filter"]=>
string(3) "raw"
}
[1]=> ....
}
解决方法
我在这里找到了解决方案:https://stackoverflow.com/a/25286095/1788961
对我来说,这段代码有效:
$idCats = array_column($product_cat_related,'term_id');
,
从WordPress 4.5.0版本开始,分类应通过$args
数组(see get_terms()
documentation)中的“分类”参数传递。
当查询的对象是一个分类术语时,get_queried_object()
也已经给出了WP_Term
对象。
另外,您可以在'fields' => 'ids'
中将get_terms()
用作参数,以仅获取项ID 的数组,而不是WP_term
对象的数组(请参见WP_Term_Query
available arguments)。
最后,您将使用PHP implode()
获取以逗号分隔的术语ID的字符串。
因此,您的代码将改为:
$current_term = get_queried_object(); // Already a WP_Term Object
if ( $current_term->parent > 0 ) {
$siblings_ids = get_terms( array(
'taxonomy' => 'product_cat','parent' => $current_term->parent,'exclude' => $current_term->term_id,'fields' => 'ids',) );
// Get a string of coma separated terms Ids
$siblings_list_ids = implode(',',$siblings_ids);
// Testing output
echo $siblings_list_ids;
}
经过测试可以正常工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。