Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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>
share|improve this question

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

share|improve this answer
    
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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