php - Get a list of siblings term ids from current product category in WooCommerce
问题描述
I want to retrieve a list of term Ids based on the current category ID.
At the moment I'm using the following code:
$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 ));
It's working and I get an array of the terms. But the probem is, that I only need the IDs from the term object to get a list like this:
123,345,678
Is there any way to extract such a list from the $product_cat_related
array?
This is the current output:
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]=> ....
}
解决方案
从 WordPress 4.5.0 版开始,分类法应该通过$args
数组中的“分类法”参数传递(参见get_terms()
文档)。当查询的对象是分类术语时,
也get_queried_object()
已经给出了一个对象。
您也可以在 , 中用作参数,以仅获取术语 ID数组而不是对象数组(请参阅可用参数)。
最后,您将使用 PHP获取一串以逗号分隔的术语 Id。WP_Term
'fields' => 'ids'
get_terms()
WP_term
WP_Term_Query
implode()
因此,您的代码将改为:
$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;
}
测试和工作。
推荐阅读
- javascript - 通过单个表单提交在后台选项卡中打开多个网站搜索查询
- javascript - 如何在 AngularJS 中更改 URL 并且不重新加载页面
- pandas - 在 Python 中循环移动平均线
- ios - 堆栈布局没有正确反映在模拟器上
- c++ - 为什么在等待 ICMPv6 ping 回复时调用 recv 超时?
- php - 使用准备好的语句时如何创建多维数组?
- powershell - 调用命令参数未正确传递
- css - 输入组内的输入大小 Bootstrap 4
- r - 在 Shiny 上显示图形的问题:结合聚类和线性回归
- angular7 - 如何解决 Angular 7 项目中的插值错误