show WordPress posts under subcategory only, not category

I am using this code to display subcategory in a category

<?php $this_category = get_category($cat);

    $id = get_query_var('cat');
    $args = array(  'parent' => $id );
    $catdesc = $cat->category_description;
    foreach (get_categories($args) as $cat) 
:?>
<a href="<?php echo get_category_link($cat->term_id); ?>">
<?php echo ("$cat->cat_name"); ?></a>

    <?php endforeach ?>     

    <?php while ( have_posts() ) : the_post(); ?>

    <?php
        get_template_part( 'content/content', get_post_format() );
    ?>

    <?php endwhile; ?>

The problem is that all the posts in the category display under the category and the subcategory.

Read More

But i want to display posts under that subcategory only, not in category.

Related posts

Leave a Reply

1 comment

  1. Try this:
    
    $category = 'Jobs';
    
    $categoryID = get_cat_ID($category);
    
    $subcategories = get_categories('child_of=' . $categoryID);
    
    foreach($subcategories as $subcategory) {
    
       $subcategory_posts = get_posts('cat=' . $subcategory->cat_ID);
    
       foreach($subcategory_posts as $subcategory_post) {
    
               $postID = $subcat_post->ID;
    
               echo get_the_title($postID);
       }
    }
    
    For more details go to this https://wordpress.org/support/topic/how-to-list-posts-by-sub-category