`Get_Terms()`,其中`Child_of`和`Child_less`组合

时间:2018-05-29 作者:rassoh

我有一个层次分类法filter 包含自定义类型帖子的位置和类型artist:

- Genre
-- Hip Hop
-- Trap
-- Rap
- Location
-- Europe
--- Germany
--- Sweden
--- Austria
-- Asia
--- China
--- Japan
--- Taiwan
现在,我想使用get\\u terms()只获取国家(Location的子级,没有自己的子级)。我想这应该行得通:

$location_parent = get_term(123, \'filter\');

$countries = get_terms(array(
  \'taxonomy\' => $location_parent->taxonomy,
  \'hide_empty\' => false,
  \'child_of\' => $location_parent->term_id, 
  \'childless\' => true
));
。。。但不知怎么的,事实并非如此。child_ofchildless 似乎在妨碍对方。有什么想法吗?

2 个回复
SO网友:rassoh

好的,这就是我想到的:

function get_childless_term_children( $parent_id, $taxonomy ) {
  // get all childless $terms of this $taxonomy
  $terms = get_terms(array(
    \'taxonomy\' => $taxonomy,
    \'childless\' => true,
  ));

  foreach( $terms as $key => $term ) {
    // remove $terms that aren\'t descendants (= children) of $parent_id
    if( !in_array( $parent_id, get_ancestors( $term->term_id, $taxonomy ) ) ) {
      unset( $terms[$key] );
    }
  }
  return $terms;
}
这样做的目的是:获取所有的$parent_id.

SO网友:IvanMunoz

childless 指:

(布尔)如果分类法是层次的,则返回没有子项的术语;如果分类法不是层次的,则返回所有术语

参考号:https://codex.wordpress.org/es:Function_Reference/get_terms

我想你会发现这样的情况:

/**
 * Recursively get taxonomy hierarchy
 *
 * @source http://www.daggerhart.com/wordpress-get-taxonomy-hierarchy-including-children/
 * @param string $taxonomy
 * @param int    $parent - parent term id
 *
 * @return array
 */
function get_taxonomy_hierarchy( $taxonomy, $parent = 0 ) {
    // only 1 taxonomy
    $taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
    // get all direct decendents of the $parent
    $terms = get_terms( $taxonomy, array(\'parent\' => $parent) );
    // prepare a new array.  these are the children of $parent
    // we\'ll ultimately copy all the $terms into this new array, but only after they
    // find their own children
    $children = array();
    // go through all the direct decendents of $parent, and gather their children
    foreach( $terms as $term ) {
        // recurse to get the direct decendents of "this" term
        $term->children = get_taxonomy_hierarchy( $taxonomy, $term->term_id );
        // add the term to our new array
        $children[ $term->term_id ] = $term;
    }
    // send the results back to the caller
    return $children;
}
它应该从位置返回所有子级

我们同意吗?

结束

相关推荐

Get_the_Terms()未返回预期结果

我已经创建了3个自定义分类法来标记我的帖子。我单身。php模板我正在尝试计算术语的数量,使用get_the_terms() 对于分配给帖子的每个自定义分类法,但它并没有产生我所期望的结果。我有两个自定义分类法,分别称为“大小”和“颜色”,我从这些分类法中得到的术语数量如下:<?php $sizeCount = count(get_the_terms($post->ID, \'sizes\')); $colorCount = count(get_the_terms