我需要创建一个数组,其中包含特定父类别ID的所有子段塞。
假设我有以下父类别及其子类别:
食物比萨饼面包香蕉冰淇淋我需要一个代码/功能在里面使用functions.php
返回特定父类别的所有子级slug的slug,如下所示:
function-get-child-slug( $parentID=\'1\');
它返回以下内容:
array(\'pizza\',\'bread\',\'banana\',\'ice-cream\')
我尝试了一些这方面的变体,但没有成功:
$var = wp_list_categories( array(
\'child_of\' => 1,
\'echo\' =>false
) );
$array = array(strip_tags($var));
我怎样才能做到这一点?
最合适的回答,由SO网友:Howdy_McGee 整理而成
您可以使用get_terms()
要获取子段塞数组,请执行以下操作:
/**
* Get child term slugs from given term parent
*
* @param Integer $parent_id ( Parent Term ID )
* @param String $taxonomy ( Taxonomy Slug )
*
* @return Array( $term_id => $child_slug )
*/
function get_child_slugs( $parent_id = 0, $taxonomy = \'category\' ) {
return get_terms( array(
\'taxonomy\' => $taxonomy,
\'parent\' => $parent_id,
\'fields\' => \'id=>slug\',
) );
}
这应该返回一个简单的数组
array( $term_id => $term_slug )
假设提供了有效的父术语ID和有效的分类法。
SO网友:Ismail
有这个get_term_children
函数可用于列出给定类别的子类别,如果找到,则返回子类别的ID,以及get_term
可用于获取类别信息,而不仅仅是ID。
function get_child_slug($parent=1, $tax=\'category\') {
if ( !is_numeric($parent) ) {
$parent = get_term_by(\'name\', $parent, $tax);
} else {
$parent = get_term( $parent );
}
if ( empty( $parent->term_id ) )
return array();
$children = get_term_children( $parent->term_id, $tax );
if ( $children ) {
$children = array_map(\'get_term\', $children);
}
return $children;
}
下面是转储测试:
samuel@Samuel-PC:~/htdocs/multisite.dev/www$ wp eval \'print_r(get_child_slug("Food"));\'
Array
(
[0] => WP_Term Object
(
[term_id] => 3
[name] => pizza
[slug] => pizza
[term_group] => 0
[term_taxonomy_id] => 3
[taxonomy] => category
[description] =>
[parent] => 2
[count] => 0
[filter] => raw
)
[1] => WP_Term Object
(
[term_id] => 4
[name] => bread
[slug] => bread
[term_group] => 0
[term_taxonomy_id] => 4
[taxonomy] => category
[description] =>
[parent] => 2
[count] => 0
[filter] => raw
)
[2] => WP_Term Object
(
[term_id] => 5
[name] => banana
[slug] => banana
[term_group] => 0
[term_taxonomy_id] => 5
[taxonomy] => category
[description] =>
[parent] => 2
[count] => 0
[filter] => raw
)
[3] => WP_Term Object
(
[term_id] => 6
[name] => ice cream
[slug] => ice-cream
[term_group] => 0
[term_taxonomy_id] => 6
[taxonomy] => category
[description] =>
[parent] => 2
[count] => 0
[filter] => raw
)
)
希望这有帮助。