Search code examples
wordpress

How To Get the children of the parent category by parent id in wordpress


i try to get All child categories from my parent category like my parent category is news and child is news1 news 2 news 3


Solution

  • This code will display all the child categories of selected parent category, tested and works in category.php template file...

    $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-->';
        }