How can I get all subcategories and the posts related to it

 $term = get_queried_object();
    if($term->post_parent !=0 ){ 

    //  echo 'has parent'; //this post category has child
    $term_id = $term->term_id;
    $taxonomy_name = $term->taxonomy;
    $termchildren = get_term_children( $term_id, $taxonomy_name );
     // echo    $postcat ;
     foreach ($termchildren  as $child) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
             // get the categories and if have subcategory get it 

             <?php }?>

     <?php   }
          //the posts in a subcategory 
       // get the subcategory posts

<?php endwhile ?>
<?php  }?>

Note: this is a code for custom taxonomy and the code here exist in a file called taxonomy-($taxonomy_name)


Try using these codes:

if( isset( $sub_category ) ){ 
 echo '<b>more items in: </b>' . $sub_category->name;
 $args = array(
 'cat' => $sub_category->term_id,
 'post__not_in' => array( get_the_ID() )
 $relatedpostsinsubcategory = new WP_Query( $args );
 if( $relatedpostsinsubcategory->have_posts() ){
 while( $relatedpostsinsubcategory->have_posts() ){

 <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> 

You can find more information about getting subcategories and related posts here.

  • i rally appreciate your help and answer but the situation is that i have a page that contain categories , some of them have subcategories , then posts related to this subcategories , i need the user to show easily this structure , my code get only until the subcategories and every time i try to access the subcategory it reload the category page again with the same subcategory ,so if you can help me and tell me what the wrong with my code i thinks it have a mistake but i can't get it – Nader Elsayed Jan 3 '19 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.