Exclude Current Post from Recent Posts Loop

Quick Summary

  • Pass array($post->ID) to the post__not_in argument of get_posts() so a recent posts list leaves out the post being read.
  • The example sets numberposts to 5, offset to 0 and category to 7; change the category ID or remove it to include all categories.
  • Use it in single.php; inside your own function declare global $post or use get_the_ID(), and call wp_reset_postdata() after setup_postdata() loops.

On a single post page, a recent posts list often includes the very post the visitor is reading. The post__not_in argument fixes that: pass it the current post’s ID, as in 'post__not_in' => array( $post->ID ), and WordPress leaves that post out of the results.

PHP
$args = array(
    'numberposts' => 5,
    'offset' => 0,
    'category' => 7,
    'post__not_in' => array( $post->ID )
);
$myposts2 = get_posts($args);

How it works

  • numberposts sets how many posts get_posts() returns, here 5.
  • offset skips that many posts from the start; 0 starts with the newest.
  • category limits the list to the category with ID 7. Change it to your own category ID, or remove the line to include all categories.
  • post__not_in takes an array of post IDs to exclude. $post->ID is the ID of the current post.

Use the code in single.php or another template that runs on the post page. $post is the global post object, so inside your own function declare global $post; first or use get_the_ID() instead.

get_posts() returns an array of post objects in $myposts2. Loop over it with foreach to print each title and link, and if you use setup_postdata() for template tags inside that loop, call wp_reset_postdata() afterwards. A complete loop of that kind is in showing recent posts with get_posts().

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More