2016-05-13 85 views

回答

0

此代碼將選定的父類中,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-->'; 
    } 
3

使用下面的代碼獲取父類別的子類別。

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

} 
?>