How to show posts from a certain subcategory in WordPress

You are currently viewing How to show posts from a certain subcategory in WordPress

How to show posts from a certain subcategory in WordPress

In WordPress, you can use the query_posts function to show posts from a certain category or subcategory. Here’s an example of how to use it to display all posts from a subcategory called “subcat” that is a child of a parent category called “parentcat”:

Copy code<?php
$args = array(
    'cat' => 'parentcat',
    'child_of' => 'parentcat',
    'child_of' => get_cat_ID( 'subcat' )
);
query_posts( $args );
if ( have_posts() ) : while ( have_posts() ) : the_post();
    // Your post content here
endwhile; endif;
wp_reset_query();
?>

You can use the get_cat_ID function to get the ID of the subcategory, and then pass that ID as a value for the child_of parameter in the $args array. The query_posts function will then retrieve all posts that are assigned to that subcategory.

You can use the the_post() function inside the loop to display the post titles and the the_content() function to display the post content.

Note that the query_posts() function is not recommended to use in WordPress, as it modifies the main query and can cause unexpected behavior. Instead you can use WP_Query class.

Copy code$args = array(
    'cat' => 'parentcat',
    'child_of' => 'parentcat',
    'child_of' => get_cat_ID( 'subcat' )
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) {
    $query->the_post();
    // Your post content here
}
wp_reset_postdata();

This will display the posts that are assigned to the subcategory you specified in a similar way as query_posts()

if you need any help in wordpress development click here

Leave a Reply