How to limit the general number of WordPress posts from two different loops

1

Hello

I have two loops in my WP index, but I need a maximum of 3 posts in total. If I decrease the number of posts per page to 3, it will change that to EVERY one of the loops, except that I need to limit the number of posts TOTAL to 3.

Is there any way to do this?

Thank you!

    
asked by anonymous 19.04.2017 / 22:12

1 answer

1

For each loops , simply add the posts_per_page paging parameter to add the last 3 posts . (See paging parameters here). This way you will have something like

$query1 = new WP_Query('posts_per_page=3');
$query2 = new WP_Query('posts_per_page=3');

If you want 3 specific posts , you have to provide their IDs

$query1 = new WP_Query('post__in' => array( 2, 5, 12 ));

Separate the queries objects into different variables, so manipulating both loops becomes simpler.

EDIT

I confess that I struggled a little to understand your question, but come on. You are looking to show just 3 posts from both the first and the second query . Invariably, you will have to make two inquiries. What can help you here are 2 properties that the WP_Query class has: $post_count and $found_posts (See these and other properties of class here ). Here is a small example of how you can architect your code:

$args1 = array(
    'posts_per_page' => 3,
    'post_type' => 'post_type1'
);

$query1 = new WP_Query($args1);

$count = $query1->post_count;

if($count < 3) { //você tem 2, 1 ou 0 posts nessa consulta

    $args2 = array(
        'posts_per_page' => 3 - $count, // a diferença
        'post_type' => 'post_type2'
    );

    $query2 = new WP_Query($args2);

    # ...
}

And from that point, you mount your loops with the presence (or not) of the object $query2 .

    
19.04.2017 / 23:37