get_posts with multiple categories

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?

Solutions Collecting From Web of "get_posts with multiple categories"

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

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.

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.

Actually you can use category__and with get_posts() directly:

$posts = get_posts(array( 'category__and' => array(1,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 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() ); ?>


            <?php endforeach; 

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