如何获取父类的父ID的孩子在WordPress

问题描述:

我尝试像我父类我父类 得到所有子类别是新闻,孩子是新闻1新闻2新闻3如何获取父类的父ID的孩子在WordPress

+0

http://stackoverflow.com/a/19503347/4034148 –

此代码将选定的父类中,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-->'; 
    } 

使用下面的代码获取父类别的子类别。

<?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>'; 

} 
?>