2

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="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
4

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

  • I had to add a definition of te post type and it worked like a charm, thanks for your help <ul> <?php global $post; $args = array( 'post_type' => 'predicadores', 'numberposts' => 4, 'orderby' => 'rand'); $tmp_post = $post; $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> <?php $post = $tmp_post; ?> </ul> – ciro Nov 29 '12 at 16:09
  • Great! I updated my answer to avoid confusion for future visitors. – Matthew Boynes Nov 29 '12 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.