Basic Query
The following query will give you the five users with the most posts in a site. Using the HAVING
and COUNT
will be much faster than other queries. Especially faster than built in multi purpose WP queries.
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 );
Random results
Now that you want to have them randomly. It's actually quite easy using the MySQL function RAND()
:
SELECT post_author, COUNT( * ) AS count
FROM {$wpdb->posts}
GROUP BY post_author
HAVING COUNT( * ) > 3
ORDER BY RAND() DESC
LIMIT 0 , 5
Excluding
To exclude a specific user by ID, we can use the NOT
statement:
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
The Plugin
To summon that in a small mu-plugin (so it is available per default on every site):
<?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 <wecodemore@gmail.com>
* 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 ) );
}
You can now simply call wpse115930UserPostCountRand( 3, array( 4 ), 5 );
anywhere in your templates to get the users who have a minimum of 5 posts, don't have the ID of 4
and limit the result to 3
users. As you can see the second argument is an array, so expanding the results to exclude more users is easy. The same goes for a different amount of users or minimum posts.
Caching results
As already mentioned, you could use the Transients API. Another and maybe even better option would be to use the WP Object Cache in above plugin. In case some sort of persistent cache like OpCode or MEMcache is involved, it will cache it to disk as well.
Have fun :)