【问题标题】:Get a list of siblings term ids from current product category in WooCommerce从 WooCommerce 中的当前产品类别中获取兄弟术语 ID 列表
【发布时间】:2020-12-24 13:27:33
【问题描述】:

我想根据当前类别 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 ));

它正在工作,我得到了一系列术语。 但问题是,我只需要术语对象中的 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]=> ....
}

【问题讨论】:

    标签: php wordpress woocommerce siblings taxonomy-terms


    【解决方案1】:

    我在这里找到了解决方案:https://stackoverflow.com/a/25286095/1788961

    对我来说,这段代码有效:

    $idCats = array_column($product_cat_related, 'term_id');
    

    【讨论】:

      【解决方案2】:

      自 WordPress 版本 4.5.0 起,分类法应通过 $args 数组中的“分类法”参数传递(see get_terms() documentation)
      当查询的对象是分类术语时,get_queried_object() 已经给出了 WP_Term 对象。
      您也可以使用'fields' => 'ids' 作为get_terms() 中的参数,以仅获取term Ids 数组,而不是WP_term 对象数组(参见WP_Term_Query available arguments) em>.
      最后,您将使用 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;
      }
      

      经过测试并且有效。

      【讨论】:

      • 我正在使用 ID 来显示该类别列表中的帖子。如果我在税务查询中使用我的方式和'terms' => $idCats,一切正常。用你的方式和'terms' => array($siblings_list_ids)我只能得到10个帖子?! 'posts_per_page' 设置为 30。
      • 好的,我想我必须使用'terms' => $siblings_ids 而不用逗号分隔 ID
      猜你喜欢
      • 2018-01-24
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      相关资源
      最近更新 更多