TheTC
TheTC

Reputation: 697

Using WP_Query twice on the same page with different results

I am trying to get recent posts, loop through those and then get the rest of the posts afterward. Here's how my loop is currently structured:

$recentArgs = array(
    'posts_per_page' => 4,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'post_type' => 'post',
    'post_status' => 'publish',
    'suppress_filters' => true
);

$recentQuery = new WP_Query($recentArgs);

$recent_post_ids = [];
foreach ($recentQuery->posts AS $recentPost) {
    $recent_post_ids[] = $recentPost->ID;
}

Then I loop through and do the HTML. Afterwards I do this:

<?php wp_reset_query(); wp_reset_postdata(); ?>

I've also tried with no luck:

<?php rewind_post(); ?>

Here is the 2nd WP_Query call, which returns the same result as above:

$allQuery = new WP_Query([
    'posts_per_page' => 10,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'post_type' => 'post',
    'post_status' => 'publish',
    'suppress_filters' => true,
    'exclude' => $recent_post_ids,
]);

I'm sure I'm missing something stupid/simple. But, any help is much appreciated.

Upvotes: 1

Views: 551

Answers (1)

TheTC
TheTC

Reputation: 697

There may be a better way to do this, but I worked around it by using get_posts() instead. So, now my first and second (with diff arguments) query looks like this:

<?php wp_reset_query(); wp_reset_postdata(); ?>

<?php
$allPosts = get_posts([
    'posts_per_page' => 10,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'post_type' => 'post',
    'post_status' => 'publish',
    'suppress_filters' => true,
    'exclude' => $recent_post_ids,
]);

Thanks again.

Upvotes: 2

Related Questions