基本查询
以下查询将为您提供网站中帖子最多的五个用户。使用
HAVING
和
COUNT
将比其他查询快得多。尤其是比内置的多用途WP查询更快。
global $wpdb;
$postCountSQL = <<<SQL
SELECT post_author, COUNT( * ) AS count
FROM {$wpdb->posts}
GROUP BY post_author
HAVING COUNT( * ) > 3
ORDER BY count DESC
LIMIT 0 , 5
SQL;
$postCount = $wpdb->get_results( $postCountSQL );
现在,您希望随机获得随机结果。实际上,使用MySQL函数很容易
RAND()
:
SELECT post_author, COUNT( * ) AS count
FROM {$wpdb->posts}
GROUP BY post_author
HAVING COUNT( * ) > 3
ORDER BY RAND() DESC
LIMIT 0 , 5
排除要按ID排除特定用户,我们可以使用
NOT
声明:
SELECT post_author, COUNT( * ) AS count
FROM {$wpdb->posts}
GROUP BY post_author
HAVING COUNT( * ) > 3
AND NOT post_author = {$id}
ORDER BY RAND( ) DESC
LIMIT 0 , 5
在一个小型mu插件中调用该插件(因此它在每个站点上都默认可用):
<?php
/**
* Plugin Name: (#115930) Random User Post Count
* Plugin URI: http://wordpress.stackexchange.com/questions/115930/how-to-randomly-list-5-authors-with-at-least-3-published-posts
* Description: Lists five random users and their posts count. Can exclude users by ID.
* Author: Franz Josef Kaiser <[email protected]>
* Author URI: http://unserkaiser.com
*/
defined( \'ABSPATH\' ) OR exit;
function wpse115930UserPostCountRand( $minCount = 3, $userIDs = array(), $limit = 5 )
{
! is_array( $userIDs ) AND $userIDs = array( $userIDs );
global $wpdb;
$sql = <<<SQL
SELECT post_author, COUNT( * ) AS count
FROM {$wpdb->posts}
GROUP BY post_author
HAVING COUNT( * ) > %d %s
ORDER BY RAND( ) DESC
LIMIT 0 , %d
SQL;
$exclude = "";
! empty( $userIDs ) AND $exclude = $wpdb->prepare(
" AND NOT post_author IN ( %s ) ",
join( ",", $userIDs )
);
return $wpdb->get_results( $wpdb->prepare( $sql, $minCount, $exclude, $limit ) );
}
您现在只需拨打
wpse115930UserPostCountRand( 3, array( 4 ), 5 );
在模板中的任何位置获取至少有5篇帖子的用户,没有
4
并将结果限制为
3
用户。如您所见,第二个参数是一个数组,因此扩展结果以排除更多用户很容易。同样的情况也适用于不同数量的用户或最少的帖子。
缓存结果
如前所述,您可以使用Transients API。另一个甚至更好的选择是使用
WP Object Cache 在上述插件中。如果涉及某种持久缓存,如操作码或MEMcache,它也会将其缓存到磁盘。
玩得开心:)