0

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?

2
// 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

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.