0

I am working on a plugin for which I need to create an array of all users (name and ID) that have one or more publish blog posts.

Looking at the documentation for get_users() it does not seem to have an arg value for this particular requirement.

How do I obtain this data?

2

There is an argument for this, and it is documented. If you look at the documentation for get_users() is says this:

See WP_User_Query::prepare_query(). for more information on accepted arguments.

If you follow that link you'll see the list of arguments, and one of those is:

'has_published_posts'

(bool|array) Pass an array of post types to filter results to users who have published posts in those post types. true is an alias for all public post types.

So you can get published authors like this:

$authors = get_users( [ 'has_published_posts' => true ] );

Or, if you just want users who have published posts:

$authors = get_users(
    [
        'has_published_posts' => [ 'post' ],
    ]
);
0

You can set "orderby" and "who" in get_users: https://codex.wordpress.org/Function_Reference/get_users

   $usersList = get_users( 'orderby=post_count&who=authors' );
      foreach ( $usersList as $user ) {
      echo '<li>' . esc_html( $user->display_name ) . '</li>';
  }
  • I know it had to be possible. Thank you. – Matthew Brown aka Lord Matt Jun 12 at 11:10
  • And you can use count_user_posts($user->ID) in this foreach loop to remove users without any post. – Bhupen Jun 12 at 11:12
  • 2
    Setting the who argument to authors limits the result to users based on their user level. It has nothing to do with whether or not the user has any posts. – Jacob Peattie Jun 12 at 11:16
-2

You can always use custom sql queries to perform things like that.

function custom_query(){
    global $wpdb;
    $tbl_users = $wpdb->prefix . "users";
    $tbl_posts = $wpdb->prefix . "posts";

    $sql = "SELECT ID, user_nicename FROM $tbl_users where ID in (SELECT post_author from tbl_posts WHERE post_status='publish' group by post_author);";
    $results = $wpdb->get_results($sql);

    if($results){
        foreach($results as $row){
            response[] = array($row->ID, $row->user_nicename);
        }
        return response;
    }else{
        return null;
    }
}

I have tested the sql command. But didn't test the complete PHP implementation. But I think you got the idea.

EDIT: I have add this method just to show that you could always go for custom queries if you stuck on something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.