最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Return all users that have one or more published blog posts

programmeradmin2浏览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?

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?

Share Improve this question asked Jun 12, 2019 at 10:55 Matthew Brown aka Lord MattMatthew Brown aka Lord Matt 1,0683 gold badges13 silver badges34 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 3

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' ],
    ]
);

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

   $usersList = get_users( 'orderby=post_count&who=authors' );
      foreach ( $usersList as $user ) {
      echo '<li>' . esc_html( $user->display_name ) . '</li>';
  }

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.

发布评论

评论列表(0)

  1. 暂无评论