If $posts contains the results of a WP_Query for posts, how can I remove one specific post by ID from the object?

I am not talking about using post__not_in prior to the query. I am talking about removing one post after the results are in.

1 Answer 1


Perhaps something like this would work?

// Assuming $posts = new WP_Query( $args );
$post_to_remove = 123;
// If using post objects
foreach ( $posts->posts as $i => $post ) {
  if ( $post_to_remove == $post->ID ) {
    unset( $posts->posts[$i] );
    break; // no need to continue the loop as the post has been found
// If only IDs were queried
foreach ( $posts->posts as $i => $post_id ) {
  if ( $post_to_remove == $post_id ) {
    unset( $posts->posts[$i] );
    break; // no need to continue the loop as the post has been found
// do your rendering while/for/foreach loop after sorting

EDIT You could also skip the post in your loop, I think.

<?php if (have_posts()) : ?>

    <?php while (have_posts()) : the_post(); ?>

        <?php if ( $post_to_remove == get_the_id() ) { continue; } ?>

    <?php endwhile; ?>

        <?php // Navigation ?>

    <?php else : ?>

        <?php // No Posts Found ?>

<?php endif; ?>
  • 2
    One issue with the second method (skipping) is that it interferes with my (Javascript) pagination - when I specify N posts per page, there is a blank space where the post in question should be, since this page is then N-1. It does work other than that. Commented Feb 28, 2019 at 10:19
  • With your first method, which is proper item removal, where does the Loop go amongst that? Is this essentially switching from a while to a foreach loop? Commented Feb 28, 2019 at 10:19
  • About the first example. You would first do your query to get posts, then do the sorting loop and after that do your Loop to display the posts. You can do it in anyway you want - for, foreach or while. Commented Feb 28, 2019 at 12:01
  • Not sure how to overcome the blank-slot issue with the first method, but the second method (simply skipping the output when the ID matches an ID to be omitted) is very straightforward. Commented Mar 3, 2019 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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