我突然想到:
echo \'<ul>\';
the_random_posts();
echo \'</ul>\';
/**
* Send random posts to the browser (STDOUT).
*/
function the_random_posts() {
// Use your own category ids.
$random_posts = array_merge(
get_random_posts( 31, 3 ),
get_random_posts( 11, 1 ),
get_random_posts( 24, 1 )
);
foreach ( $random_posts as $post ) {
// Change this line to code you want to output.
printf( \'<li><a href="%s">%s</a></li>\', get_permalink( $post->ID ), get_the_title( $post->ID ) );
}
}
/**
* Get $post_count random posts from $category_id.
*
* @param int $post_count Number of random posts to retrieve.
* @param int $category_id ID of the category.
*/
function get_random_posts( $category_id, $post_count ) {
$posts = get_posts( array(
\'posts_per_page\' => $post_count,
\'orderby\' => \'rand\',
\'cat\' => $category_id,
\'post_status\' => \'publish\',
) );
return $posts;
}
如果任何帖子位于所选类别中的2个或多个类别中,则有可能会重复一篇帖子(如同时位于a类和B类中的帖子)。A.
static variable 使用以前检索到的post数组可能会解决这个问题。
此算法按调用顺序打印帖子。
get_random_posts( 31, 3 ), // First, 3 random posts from Category A
get_random_posts( 11, 1 ), // Then, 1 random post from Category B
get_random_posts( 24, 1 ) // Then, 1 random post from Category C
如果你想要一个随机列表,
shuffle $random_posts
.