1

get_posts('numberposts=5&category=93+85')get_posts('numberposts=5&category=9385')

Is there a way to have get_posts grab only posts that are in BOTH categories, as above?

1 Answer 1

4

Use WP_Query's category__and:

$args = array(
    'posts_per_page' => 5,
    'category__and' => array( 93, 85 )
);

$my_query = new WP_Query( $args );
while( $my_query->have_posts() ):
    $my_query->the_post();
    the_title();
endwhile;

wp_reset_postdata();
8
  • Where would that go in a situation like this? <?php global $post; $myposts = get_posts('numberposts=5&category=1'); foreach($myposts as $post) : setup_postdata($post); ?>
    – Sal
    Commented Mar 6, 2013 at 21:54
  • it would replace get_posts, see edit above.
    – Milo
    Commented Mar 6, 2013 at 21:57
  • Hmm. Perhaps I mislead. I'm trying to only get posts that are in both categories at the same time. Category__and doesn't do that, no?
    – Sal
    Commented Mar 6, 2013 at 22:09
  • it does, category__in fetches posts that are in one category OR another, category__and fetches posts that have both categories.
    – Milo
    Commented Mar 6, 2013 at 22:32
  • Ah, alright. So now, and I apologize as I'm not too keen on PHP what would I replace this with: <?php global $post; $myposts = get_posts('numberposts=5&category=30'); foreach($myposts as $post) : setup_postdata($post); ?> <?php if ( in_category('1') ) { ?> <?php include('sidebar-reviews_review.php'); ?> <?php } ?> To make it pull posts from categories 30 and 1.
    – Sal
    Commented Mar 6, 2013 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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