Get Y random authors’ ID/Object with more than X number of posts

You can get rid of most of your code above. WP_User_Query has an include parameter (introduced in WordPress 3.9)

include (array) – List of users to be included.

So we need to get a random array of author ID’s. I have modified your count_users_with_posts() a bit here to extend it to make it more dynamic and to get a set amount of authors randomly. I also had to repair a few bugs (some SQL errors, specially this line: WHERE post_count > %s ORDER BY count DESC. You should enable debugging when developing 🙂)

CAVEAT: This works on my local install with 4 users.

function get_author_posts_count( $min_posts = 1, $max_posts = 10, $limit = 10, $post_type="post" )
{
    global $wpdb;

    $authors = $wpdb->get_col(
        $wpdb->prepare(
            "SELECT post_author FROM (
                SELECT post_author, COUNT(*) AS count 
                FROM $wpdb->posts
                WHERE post_type = %s 
                AND post_status="publish" 
                GROUP BY post_author
            ) AS stats
            WHERE stats.count BETWEEN %d AND %d
            ORDER BY RAND()
            LIMIT 0,%d",
            $post_type,
            $min_posts,
            $max_posts,
            $limit
        )
    );

    return $authors;
}

As you can see, I have included 4 parameters here.

  • $min_posts -> Minimum amount of published posts an author must have. Default 1

  • $max_posts -> As you would like to get authors with low post count, I have included a maximum post count. You can remove that if you wish, just remember to change the SQL accordingly then Default 10

  • $limit -> The amount of post authors to get. Default 10

  • $post_type -> The post type to get use. Default post

You can then use the function above in your WP_User_query as follow

$args = [
    'include' => get_author_posts_count( 5, 20, 5, 'my_post_type' )
];

$authors = new WP_User_Query( $args );

EDIT

From comments (thanks @birgire), there are a few issues that you should take note of

  • Before passing the result of get_author_posts_count() to the include parameter of WP_User_Query, you should check whether or not if any values are available. If the result of get_author_posts_count() is empty or invalid, the include parameter will be ignored and all users will be returned. The query will not return an empty array of users

  • There is a limit on the lenght of an SQL query, so very big author queries might crash. As I already stated, my test site is really small, so I cannot test my code to the max. You should also check out this post on SQL query lentghs

I would appreciate any feedback on tests on large sites with many posts and plenty authors

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)