WP_Query: show all posts except the current post
This came up when setting up this very blog. I don’t need anything fancy yet like filtering by category, but do want to show a list of other posts at the bottom of each post – except I don’t want to link to the current post, because that’s obviously redundant.
There is a simple way to use WP_Query()
to set up a new query and do that:
<?php
$the_query = new WP_Query([
'post_type' => 'post',
'post__not_in' => [get_the_id()]
]);
while ( $the_query->have_posts() ): $the_query->the_post();
?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
... anything else you want to display from your posts ...
<?php endwhile; ?>
The important part of this is happening inside new WP_Query()
– the array firstly says show everything where post_type
is a post
(ie. not a page
or anything else), and then post__not_in
is passed an array that only includes the ID of the current post from get_the_id()
. In other words, “all posts, where the ID does not match the ID of the current post”.
After that, we re-run the standard Wordpress loop, but notice that the calls to have_posts()
and the_post()
are now made on our new query object, $the_query
. If you forget to use $the_query->the_post()
and instead just put the_post()
, the result will be an infinite loop! (Ask me how I know.)
You can also run multiple queries with any combination of filters you like – just use a different variable each time where the above code uses $the_query
.