0

I have a website. There the following structure:

Parent Category:
Child category 1
Child category 2

In Parent Category I need display all posts of child category.

I write next WP query:

<?php
    $child_pages = new WP_Query(array(
        'post_type' => 'post',
        'category__in' => 5,
        'posts_per_page' => 3,
        'order' => 'ASC',
        'orderby' => 'title',
    )
);
?>

For the argument 'category__in' I set Parent category ID (its Parent category ID). But it is not working. In parent category posts not displayed.

How i get all child category posts on parent category?

Guys, and sorry for my English. Im in learning.. Yes, I'm ashamed))

0

You need to use a tax_query with WP_Query. With a tax_query, by default, child terms are included to the term being set. Here is the example-

$args = array(
      'post_type'      => 'post', // Your post type
      'orderby'        => 'meta_value_num', 
      'meta_key'       => 'rankk', 
      'order'          => 'DESC', 
      'posts_per_page' => 100,
      'tax_query' => array(
            array(
                'taxonomy'         => 'category', // Taxonomy name
                'field'            => 'term_id', // Means you'll use term id to determine your parent term.
                'include_children' => true,
                'operator'         => 'IN'
                'terms'            => 'YOUR PARENT CATEGORY ID', // Your term or category ID
            ),
        ),
);

$q = new WP_Query( $args );

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

Hope this above helps.

6
  • Thank you sir for answer! And in the field 'term_id' I should set child categories ID? I mean argument 'field' => 'term_id'. Can I get all child categories posts? – Alex Gromov Sep 5 '18 at 8:03
  • @AlexGromov Please see my updated answer, I made it clear. And if this helps you then please accept the answer by clicking the check sign or tick mark at the left of my answer. – CodeMascot Sep 5 '18 at 8:11
  • Please, sir, let me one question. We have field: 'terms' => 'YOUR PARENT CATEGORY ID', How correctly I should set Parent category ID? Just write ID number? – Alex Gromov Sep 5 '18 at 8:17
  • Yes. Write the ID number as a string or as far I can remember, you can pass an array too. Like either 'terms' => '23', or 'terms' => 23, or 'terms' => array( 23 ),. As you like. But remember here 23 is just a place holder, use your term ID. – CodeMascot Sep 5 '18 at 8:20
  • Thank you, sir! Thank you my American friend! Hello from Russia. Your code is working and help me. – Alex Gromov Sep 5 '18 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.