我有一个层次分类法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_of
和
childless
似乎在妨碍对方。有什么想法吗?
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;
}
它应该从位置返回所有子级
我们同意吗?