5

If I do a get_posts() with category set to 1,2 I will get all posts in category 1 OR 2. If i want all posts whit both categories, that is 1 AND 2, how do I make that request?

6 Answers 6

10

As documented in the codex you could use the following

$query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) ); //post has to be in category with ID 2 AND 6

3

The Codex says:

Note: The category parameter needs to be the ID of the category, and not the category name.

Note: The category parameter can be a comma separated list of categories, as the get_posts() function passes the 'category' parameter directly into WP_Query as 'cat'.

So it'd be same as WP_Query()'s Category parameter - cat.

1
  • Wow, i took for granted that this would give the same result. My bad. Thanks.
    – gubbfett
    Apr 21, 2015 at 15:02
3

You can use the WP_QUERY class to search for the posts in some specific categories, here is an example:

$query = new WP_Query( 'cat=2,6,17,38' );

Here is a link to the documentation where they explain how to use the results to build a loop and display the posts in the results.

2

Actually you can use category__and with get_posts() directly:

$posts = get_posts(array( 'category__and' => array(1,2) ));
2

There is a much easier way that just involves the get_posts() function.

<?php $args1 = array( 'posts_per_page' => 6, 'offset'=> 0, 'category' => array(2,3,25,30));
            $myposts1 = get_posts( $args1 );
            foreach ( $myposts1 as $post ) : setup_postdata( $post ); ?>
            <div class="each-post col-lg-aynk col-md-aynk col-sm-aynk col-xs-aynk">
                <a href="<?php the_permalink(); ?>">
                    <h2><?php the_title(); ?></h2>
                </a>
                <a href="<?php the_permalink(); ?>">
                    <div class="news-story-img">
                        <?php if (class_exists('MultiPostThumbnails')) : MultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-image'); endif; ?>
                        <?php the_post_thumbnail( get_permalink() ); ?>
                    </div>
                </a>

            </div>

            <?php endforeach; 
            wp_reset_postdata();?>
2
  • 2
    Please explain why this helps.
    – kaiser
    Mar 13, 2016 at 22:58
  • I can't vote to delete, but the code doesn't even match the comment regarding get_posts(). Dec 29, 2016 at 17:13
0

If you want to use category_name as search parameter, you can use WP_Query( array("category_name" => "cat_1+cat_2+...+cat_n") ), where cat_1, cat_2, ... , cat_n are all the categories that the post must have to be returned from the query

Documentation here Codex Wordpress

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.