获取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;
}

经过测试可以正常工作。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...