这是我到目前为止所拥有的东西的草稿。请随时更新和改进。
首先,我们使用pre_user_action
选择用户获取并显示其信息所需的最少帖子数。它是从WP_User_Query to exclude users with no posts (作者:helgatheviking)。我只是做了一些小改动来满足我的需要。
add_action( \'pre_user_query\', \'users_with_posts\',10, 1 );
function users_with_posts( &$query) {
global $wpdb;
$min_posts = 5;
if ( isset( $query->query_vars[\'query_id\'] ) && \'wps_last_name\' == $query->query_vars[\'query_id\'] )
$query->query_from = $query->query_from . " LEFT OUTER JOIN (
SELECT post_author, COUNT(*) as post_count
FROM $wpdb->posts
WHERE post_type = post AND post_status = publish
GROUP BY post_author
) p ON ({$wpdb->users}.ID = p.post_author)
";
$query->query_where = $query->query_where . " AND post_count > {$min_posts} ";
}
然后,我们需要发布超过X个帖子的用户总数。
function count_users_with_posts($min_posts) {
global $wpdb;
$author_ids = $wpdb->get_col($wpdb->prepare("SELECT post_author FROM
(SELECT post_author, COUNT(*) AS post_count FROM {$wpdb->posts}
WHERE post_type = \'post\' AND post_status=\'publish\' GROUP BY post_author) AS stats
WHERE post_count > %s ORDER BY count DESC;",$min_posts));
return count($author_ids);
}
现在,我们准备好继续并使用
WP_User_query()
函数获取“随机”用户。他们不是100%随机选择的,但这是我能得到的最接近的。
以下是我们函数的参数:
$args = array (
\'query_id\' => \'users_with_posts\',
\'orderby\' => \'post_count\',
\'order\' => \'ASC\', //default
\'number\' => $total_number,
\'offset\' => $offset,
);
你可以看到,我们缺少了两个变量,这就是我们要玩的地方。我们将生成一个随机偏移以获得“随机”效果。
$total_number = 12; //number of users we want to display
$total_authors = count_users_with_posts(5); //total number of users with more than 5 posts
$offset = mt_rand(0,$total_authors - $total_number); //randomly generated offset.
$users = new WP_User_Query( $args );
还有很多改进的空间,我希望有人从这里开始,或者如果有不同的更好的方法,欢迎您分享。