1

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:

<?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.

2 Answers 2

0

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

0
1

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.

1
  • I ran the function and it returned something: WP_Post Object ( [ID] => 489 [post_author] => 1 [post_date] => 2013-03-11 22:54:27 [post_date_gmt] => 2013-03-11 22:54:27 [post_content] => and then I put in $args = array( 'numberposts' => 3, 'exclude' => $post->id,'orderby' => 'rand' ); and it still showed the single in the random posts
    – Jacob
    Commented May 9, 2013 at 2:16

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.