对于数量相对较少的帖子,您可以尝试以下方法:
/**
* Return a single random search result
*/
add_action( \'pre_get_posts\', function( \\WP_Query $q )
{
if( ! is_admin() && $q->is_main_query() && $q->is_search() )
{
$q->set( \'posts_per_page\', 1 );
$q->set( \'orderby\', \'rand\' );
}
} );
其中,我们修改了主前端搜索查询。
请注意,随机排序不能很好地扩展
另一种方法是从搜索查询中获取最多15篇帖子,按随机顺序排列这些帖子,然后显示单个帖子:
/**
* Return max 15 posts from the search results, ignore paging
* and then only display a single random post
*/
add_action( \'pre_get_posts\', function( \\WP_Query $q )
{
if( ! is_admin() && $q->is_main_query() && $q->is_search() )
{
$q->set( \'posts_per_page\', 15 );
$q->set( \'no_found_rows\', true ); // ignore paging
// Display only a single random post from these 15
add_filter( \'the_posts\', \'wpse_random_post\' );
}
} );
/**
* Return a single random post from the posts results array.
*/
function wpse_random_post( Array $posts )
{
remove_filter( current_filter(), __FUNCTION__ );
if( count( $posts ) > 0 )
$posts = [ $posts[array_rand( $posts )] ];
return $posts;
}