How to get WP_Query() to return posts from a subcategory
-
Hi everyone,
I am currently working on an old WordPress website (that is currently offline) and modifying some templates to refresh its theme, but I struggle to get the result I want for the category.php page. My goal is to group posts by subcategory, like this :
Category 1
Subcategory 1A
- Post 1
- Post 2
Subcategory 1B
- Post 3
- Post 4
Category 2 :
Subcategory 2A
- Post 6
- Post 7
Subcategory 2B
- Post 8
- etc..
To do so, I use the get_terms() function to fetch all the subcategories of the current category, use a loop to display the name of each subcategory and WP_Query() within the loop to fetch and display the posts of the currently selected subcategory.
The first part works as expected and properly displays all the subcategories of the current category as titles. The second part however, always returns all the posts from the current category, and not the associated subcategory. Basically the result is this :
Category 1
Subcategory 1A
- Post 1
- Post 2
- Post 3
- Post 4
Subcategory 1B
- Post 1
- Post 2
- Post 3
- Post 4
Currently my code is as follow :
<?php $child_cats = get_terms( array( 'taxonomy' => 'category', 'parent' => $cat_active, 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => FALSE, )); foreach ($child_cats as $child_cat ) : $subcat_name = $child_cat -> name; $subcat_id = $child_cat -> term_id; $subcat_slug = $child_cat -> slug; ?> <div class= "subcategory-post-list subcategory-<?php echo $subcat_id; ?>"> <h3 class="subcategory-title"><?= $subcat_name ?></h3> <?php $args = array( 'post_type' => 'post', 'cat' => $subcat_id, ); $posts = new WP_Query($args); if ($posts->have_posts()) : while ($posts->have_posts()) : $posts->the_post(); ?> <p> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </p> <?php endwhile; else: echo 'No posts found'; endif; wp_reset_postdata();?> </div> <?php endforeach; ?>
The issue seems to be that the argument
'cat' => $subcat_id
is not applied by the second query, but I don’t know what to change to get the result I am looking for. Any idea of what I am doing wrong ?Thank you in advance for your help
- The topic ‘How to get WP_Query() to return posts from a subcategory’ is closed to new replies.