How to show posts from a single category in WordPress archive?

Hey everyone,

I’ve been working on a custom WordPress setup that’s almost finished. But I’m stuck on one last thing. I want to create a page that only shows posts from one specific category and its subcategories. The regular archive page shows everything, which isn’t what I need.

Does anyone know how to make this work? I’ve tried a few things but can’t seem to get it right. Any tips or code examples would be super helpful!

Thanks in advance for your help. I’m really excited to get this final piece sorted out!

To display posts from a specific category and its subcategories in WordPress, you can utilize a custom WP_Query. In your theme’s archive.php or a custom template, replace the standard loop with a new query. Set the ‘category__in’ parameter to include your target category ID and use ‘get_term_children()’ to fetch subcategories. This approach offers more control over the output compared to modifying the main query. Remember to paginate results for better performance if you have numerous posts. If you need help implementing this solution, I’d be happy to provide more detailed guidance.

hey finn_mystery! you can use the pre_get_posts hook in your functions.php to filter category archives. by chekc if in category archive and setting the query, u’ll get posts from that category and subcats. hope that helps!

I’ve tackled this issue before in one of my projects. The solution that worked best for me was creating a custom template file specifically for the category you want to display. Name it something like category-yourslug.php and place it in your theme folder.

In this template, you can use a custom WP_Query to fetch only the posts from your desired category and its subcategories. Here’s a rough outline of what the code might look like:

$category = get_queried_object();
$args = array(
    'category__in' => array($category->term_id),
    'post_type' => 'post',
    'posts_per_page' => 10,
);
$query = new WP_Query($args);

if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
        // Your post display code here
    endwhile;
endif;
wp_reset_postdata();

This approach gives you full control over the display and keeps your main archive untouched. Just remember to adjust the ‘posts_per_page’ value as needed and add pagination if you have lots of posts.