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 want to display a single random post out of the 5 latest posts in the category 'news'.
The approach I'm using is this:

  // Custom function to retrieve catgory ID by category name.
  $cat = $lib->getCatIDbyCatName('news');
  // Retrieve the 5 latest posts
  $news = get_posts( array( 'numberposts' => 5,'category_name' => $cat ) );

  foreach($news as $post) : setup_postdata($post); 
    echo the_title(); 
    echo the_intro(); // <- Custom function to retrieve custom field
  endforeach;

The above code works and I'm dispalying the title and the custom value of all 5 posts. Now I only want one random post out of these 5 posts. So I do this:

  // Get a single random post from fetched posts
  $single_news = $news[rand(0, 4)];

  foreach($single_news as $post) : setup_postdata($post); 
    echo the_title(); 
    echo the_intro(); // <- Custom function to retrieve custom field
  endforeach;

This however, is not working.

Does anyone have any ideas of what I can do? OR maybe a better solution?

share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted
// Get a single random post from fetched posts   
  $post = $news[rand(0, 4)];    
  setup_postdata($post);     
   echo the_title();      
   echo the_intro(); // <- Custom function to retrieve custom field
share|improve this answer
add comment

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.