Not able to get random post

时间:2011-05-15 作者:Steven

我想显示“新闻”类别中5篇最新帖子中的一篇随机帖子
我使用的方法是:

  // 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;
以上代码有效,我正在显示所有5篇文章的标题和自定义值。现在我只想在这5篇帖子中随机选一篇。所以我这样做:

  // 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;
然而,这是行不通的。

有人知道我能做什么吗?或者更好的解决方案?

1 个回复
最合适的回答,由SO网友:Michael 整理而成
// 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
结束

相关推荐