如何从某个类别中获取所有子类别?
列出类别中的所有子类别
2 个回复
最合适的回答,由SO网友:Bainternet 整理而成
是的,您可以使用get_categories() 使用\'child_of\'
属性例如,ID为17的类别的所有子类别:
$args = array(\'child_of\' => 17);
$categories = get_categories( $args );
foreach($categories as $category) {
echo \'<p>Category: <a href="\' . get_category_link( $category->term_id ) . \'" title="\' . sprintf( __( "View all posts in %s" ), $category->name ) . \'" \' . \'>\' . $category->name.\'</a> </p> \';
echo \'<p> Description:\'. $category->description . \'</p>\';
echo \'<p> Post Count: \'. $category->count . \'</p>\';
}
这将获得作为子代的所有类别(即子代和孙代)。如果要仅显示直接子类的类别(即仅限子类),可以使用\'parent\'
属性
$args = array(\'parent\' => 17);
$categories = get_categories( $args );
foreach($categories as $category) {
echo \'<p>Category: <a href="\' . get_category_link( $category->term_id ) . \'" title="\' . sprintf( __( "View all posts in %s" ), $category->name ) . \'" \' . \'>\' . $category->name.\'</a> </p> \';
echo \'<p> Description:\'. $category->description . \'</p>\';
echo \'<p> Post Count: \'. $category->count . \'</p>\';
}
SO网友:Fanky
对于自定义帖子类型“;“类别”;使用get_terms().
(更改@Bainternet的答案)
$categories = get_terms( array(
\'taxonomy\' => \'product_cat\',
\'hide_empty\' => false,
\'parent\' => 17 // or
//\'child_of\' => 17 // to target not only direct children
) );
foreach($categories as $category) {
echo \'<p>Category: <a href="\' . get_category_link( $category->term_id ) . \'" title="\' . sprintf( __( "View all posts in %s" ), $category->name ) . \'" \' . \'>\' . $category->name.\'</a> </p> \';
echo \'<p> Description:\'. $category->description . \'</p>\';
echo \'<p> Post Count: \'. $category->count . \'</p>\';
}
结束