Get random custom posts from a custom post type

I created a custom post type named predic, I’m trying to get within one of this post other four random posts from the same custom post type. I used this code, but I keep getting the same post I’m in 4 times.

<ul>
<?php
$rand_posts = get_posts('numberposts=4&orderby=rand');
foreach( $rand_posts as $post ) :
?>
<li><a href="https://wordpress.stackexchange.com/questions/74243/<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>

1 Answer
1

You need to include setup_postdata($post); in your foreach line. Here’s some great demo code from the codex, adopted to fit your query:

<ul>
<?php
global $post;
$tmp_post = $post;
$myposts = get_posts( 'post_type=predic&numberposts=4&orderby=rand' );
foreach( $myposts as $post ) : setup_postdata($post); ?>
    <li><a href="https://wordpress.stackexchange.com/questions/74243/<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
<?php $post = $tmp_post; ?>
</ul>

Note that we’re also resetting $post back to the current post, so we don’t break other functionality.

Leave a Comment