Exclude post ID from wp_query

I suppose this was heavy, but to answer your original question, I’ve collected all of the posts id’s in an array in the first loop, and excluded those posts from the second loop using ‘post__not_in’ which expects an array of post id’s

<?php
$args1 = array('category_name' => 'test-cat-1', 'order' => 'ASC');
$q1 = new WP_query($args);
if($q1->have_posts()) :
$firstPosts = array();
    while($q1->have_posts()) : $q1->the_post();
        $firstPosts[] = $post->ID; // add post id to array
        echo '<div class="item">';
        echo "<h2>" . get_the_title() . "</h2>";
        echo "</div>";
    endwhile;
endif;
/****************************************************************************/
// array of post id's collected in first loop, can now be used as value for the 'post__not_in' parameter in second loops query $args
$args2 = array('post__not_in' => $firstPosts, 'order' => 'ASC' );
$q2 = new WP_query($args2);
if($q2->have_posts()) :
    while($q2->have_posts()) : $q2->the_post();
        echo '<div class="item">';
        echo "<h2>" . get_the_title() . "</h2>";
        echo "</div>";
    endwhile;
endif;
?>

The first loop displays all posts in a category, and collects the post id’s into an array.

The second loop displays all posts, excluding posts from the first loop.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)