Get posts from child categories with parent category ID

As I have stated in my comments to your question

Crappy written plugins always leads to some disaster at some time. In my opinion, delete that plugin and write your own code or find a properly written plugin. There is no use changing the damaged tire while the whole car is a complete write-off 🙂

Just to start off, never use query_posts

Note: This function isn’t meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination).

You are really better off here to write your own code and discard the plugin. You can also merge the current plugin (only the “good” code) with the code I will give you into your own plugin if this is needed.

You should never ever make any changes to plugin/theme files that you are not the author of. The biggest reason is, come update day, you will loose all you customization. Rather create your own plugin or do the changes in a child theme

What you want to accomplish is not doable with the current category parameters. You best bet here will be to use a tax_query with WP_Query. With a tax_query, by default, child terms are included to the term being set, and this is what you are looking for

You can try the following (PLEASE NOTE: this requires PHP 5.4+)

$args = [
      'post_type' => 'post', 
      'orderby' => 'meta_value_num', 
      'meta_key' => 'rankk', 
      'order' => 'DESC', 
      'posts_per_page' => 100,
      'tax_query' => [
            [
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => 'YOUR PARENT CATEGORY ID',
            ],
        ],
];

$q = new WP_Query( $args );

if ( $q->have_posts() ) {
    while ( $q->have_posts() ) {
        $q->the_post();
        the_title();
    }
    wp_reset_postdata();
} 

For PHP versions prior to 5.4 try this

$args = array(
      'post_type' => 'post', 
      'orderby' => 'meta_value_num', 
      'meta_key' => 'rankk', 
      'order' => 'DESC', 
      'posts_per_page' => 100,
      'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => 'YOUR PARENT CATEGORY ID',
            ),
        ),
);

$q = new WP_Query( $args );

if ( $q->have_posts() ) {
    while ( $q->have_posts() ) {
        $q->the_post();
        the_title();
    }
    wp_reset_postdata();
} 

Leave a Comment