Display random posts, but omit the post it is on?

I am trying to have a section under a single post where it displays completely random posts. I got everything working, but every once in a while one of the random posts that get displayed is the actual post that it is on (the single).

Here is my code:

Read More
<?php
$args = array( 'numberposts' => 3, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<?php endforeach; ?>

Is there anyway to not have it ever display the post it is on?

Thank you.

Related posts

2 comments

  1. Check to see if you have a post ID (which you should on a single post page but I am not sure if this is in single.php or some other template like index.php) and add that to the $args if you do.

    $args = array( 'numberposts' => 3, 'orderby' => 'rand' );
    if (is_singular() && isset($post->ID)) {
      $args['exclude'] = array($post->ID);
    }
    $rand_posts = get_posts( $args );
    

    Reference

    http://codex.wordpress.org/Function_Reference/is_singular
    http://codex.wordpress.org/Template_Tags/get_posts
    http://codex.wordpress.org/Function_Reference/get_pages

  2. Just before this you can run <?php print_r( $post ); ?> and if it returns an array, then you can add a parameter 'exclude' => $post->id,

    Remove the print_r(); function after you’ve tested.

Comments are closed.