3

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?

9

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.

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

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.

1

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
    Please explain why this helps. – kaiser Mar 13 '16 at 22:58
  • I can't vote to delete, but the code doesn't even match the comment regarding get_posts(). – Alexander Holsgrove Dec 29 '16 at 17:13
0

Actually you can use category__and with get_posts() directly:

$posts = get_posts(array( 'category__and' => array(1,2) ));
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, privacy policy and cookie policy

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