我尝试从父类别中获取所有子类别 像我的父类别是新闻,孩子是news1 news 2 news 3
答案 0 :(得分:6)
使用以下代码获取父类别的子类别。
<?php
$parent_cat_arg = array('hide_empty' => false, 'parent' => 0 );
$parent_cat = get_terms('category',$parent_cat_arg);//category name
foreach ($parent_cat as $catVal) {
echo '<h2>'.$catVal->name.'</h2>'; //Parent Category
$child_arg = array( 'hide_empty' => false, 'parent' => $catVal->term_id );
$child_cat = get_terms( 'category', $child_arg );
echo '<ul>';
foreach( $child_cat as $child_term ) {
echo '<li>'.$child_term->name . '</li>'; //Child Category
}
echo '</ul>';
}
?>
答案 1 :(得分:1)
此代码将display all the child categories选定的父类别,经过测试并在category.php模板文件中运行...
$this_category = get_category($cat);
//echo $this_category->cat_ID;
$parent_term_id =$this_category->cat_ID; // term id of parent term
//$termchildren = get_terms('category',array('child_of' => $parent_id));
$taxonomies = array(
'taxonomy' => 'category'
);
$args = array(
// 'parent' => $parent_term_id,
'child_of' => $parent_term_id
);
$terms = get_terms($taxonomies, $args);
if (sizeof($terms)>0)
{
echo ' <div class="categories"> ';
echo '<p> Sub Categories of '. get_cat_name( $parent_term_id ) .'</p>';
foreach ( $terms as $term ) {
$term_link = sprintf( '<div class="custom-cats"><a href="%1$s" alt="%2$s">%3$s</a></div>', esc_url( get_category_link( $term->term_id ) ),
esc_attr( sprintf( 'View all posts in %s', 'textdomain' ), $term->name ),
esc_html( $term->name ));
echo sprintf( $term_link );
}
echo '</div><!-- categories div end-->';
}