user4073933
user4073933

Reputation:

Get all posts from children categories

i need get all posts from subcategories like this:

1 - Main (id=7)

--1.1 category

--1.2 category

--1.3 category

Main category have id = 7, need ignore this category and get all post from subcategories without pagination.

Upvotes: 0

Views: 2202

Answers (1)

Paul
Paul

Reputation: 1422

First get the term children of the category:

$sub_cats = get_term_children( 7, 'category' );

This will give you and array if ids of sub-categories

Then use this array as tax query in arguments of wp_query:

$args = array(
        'post_type' => 'post',
        'tax_query' => array(
            array(
            'taxonomy' => 'category',
            'field'    => 'id',
            'terms'    => $sub_cats
        ),
    ),
);


$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
  while ( $the_query->have_posts() ) {
    $the_query->the_post();

      echo '<p>' . get_the_title() . '</p>';
}
wp_reset_postdata();
} else {}

Upvotes: 2

Related Questions