hrsetyono
hrsetyono

Reputation: 4464

Wordpress - get all posts from multiple parent categories?

let's say I have categories structure like this:

food        (id = 1)
  chicken   (id = 2)
  beef      (id = 3)

beverage     (id = 11)
  soft-drink (id = 12)
  juice      (id = 13)

branch
  ... // not important

I want to show all posts from food and beverage, so I do this:

$args = array('category__in' => array(1, 11) );
get_posts( $args );

That code doesn't work because I only tick the child category.

Of course I can do array(1, 2, 3, 11, 12, 13) but it's not DRY.

Is there a good way to get all posts using the parent category's ID?

Thanks

[My Code based on answer below]

$args = array(
  'category' => implode(",", array(1, 11) )
);
get_posts( $args );

Upvotes: 2

Views: 3707

Answers (1)

You need to use cat instead of category__in, category__in will not get the categories children. You can get this info here:

Check this:

Display posts that have this category (and any children of that category), using category id:
$query = new WP_Query( 'cat=1,11' );

That code brings any children of that category but this:

Display posts that have this category (not children of that category), using category id:
$query = new WP_Query( 'category__in=1,11' );

is getting only posts from the category with that id.

Now to pass multiple category ids to cat you can build a string with php implode function if you have the ids as array.

you can also check this example:

$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$sticky = get_option( 'sticky_posts' );
$args = array(
   'cat' => 1,
   'ignore_sticky_posts' => 1,
   'post__not_in' => $sticky,
   'paged' => $paged
);
$query = new WP_Query( $args );

I haven't tested to see if you can pass an array of cat ids like 'cat'=>array(1,11) but you can test it and see if it works.

Upvotes: 4

Related Questions