随机获取帖子非常昂贵,应该在需要的地方避免。我认为我们可以用更好的方式来做到这一点。
允许一次查询所有帖子,不考虑按日期排序。我们将只查询ID,这应该非常快
将查询结果(post ID)存储在两个变量中
将一个ID数组随机排列,然后得到前11个ID
然后,我们将从第二个数组中删除这11个ID,并获得22个ID
合并两个数组并运行最终查询
让我们尝试以下代码
$args = [ // ADJUST THESE AS NEEDED
\'posts_per_page\' => -1,
\'order\' => \'ASC\',
\'fields\' => \'ids\' // Only get post ID\'s, this also bypass object caches
];
$array_1 = $array_2 = get_posts( $args );
// Make sure we have posts and we have more than 11 posts
if ( $array_1
&& 11 < count( $array_1 )
) {
// Shuffle the first array
shuffle( $array_1 );
// Get the first 11 entries sorted randomly
$array_1_random = array_slice( $array_1, 0, 11 );
// Remove the entries from $array_1_random from $array_2
$difference = array_diff( $array_2, $array_1_random );
// Get the first 22 entries from $difference
$diff_22_IDs = array_slice( $difference, 0, 22 );
// Merge the two arrays, $array_1_random and $diff_22_IDs
$ids = array_merge( $array_1_random, $diff_22_IDs );
// Now that we have our ID\'s sorted to suite our needs, query the posts
$last_args = [ // DO NOT ADJUST THESE, SHOULD BE FINE
\'post__in\' => $ids,
\'orderby\' => \'post__in\',
\'order\' => \'ASC\',
\'posts_per_page\' => count( $ids )
];
$q = new WP_Query( $last_args );
// Output your loop
while ( $q->have_posts() ) {
$q->the_post();
the_title();
}
wp_reset_postdata(); // VERY VERY IMPORTANT
}
一些注释根据需要调整代码。你应该改变一下
$last_args
虽然
您说过您需要一页,因此无需设置paged
参数,因为我们将不分页。如果需要分页,则需要稍微调整我的代码
\'max_num_pages\'
不是有效参数