How to limit the overall number of Wordpress posts from two different loops

Asked

Viewed 423 times

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 this to EACH of the loops, only I need to limit the number of posts to 3 TOTAL.

There’s a way to do it?

Thank you!

  • Are you using the WP_Query to generate these loops?

  • Yeah, that’s right!

1 answer

1


For each of the loops, just add the pagination parameter posts_per_page, to add the last 3 posts. (See the pagination parameters here). This way, you’ll have something like

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

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

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

Separate objects from the darlings in different variables, thus the manipulation of both loops becomes simpler.

EDIT

I confess that I struggled a little to understand your question, but come on. You try to show only 3 posts, from both the first and the second query. Invariably, you will have to make two queries. What can help you here are 2 properties that class Wp_query possess: $post_count and $found_posts (See these and other class properties here). See a reduced 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 on, you ride your loops with the presence (or not) of the object $query2.

  • I get it. In fact, it is already as I am doing, but I needed that if I had 3 in the first, I would have 0 in the second; if I had 2 in the first, 1 in the second; if I had 1 in the first, 2 in the second and so on... There’s no way?

  • @Alceu yes. see the edited reply =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.