Get all authors with at least one post of ‘custom post type’

How can i achive that?
I found count_user_posts and get_users, but how would I merge them into the desired result? Do I really have to use a WP DB Query?

Related posts

2 comments

  1. For now post_type support is not currently available for count_user_posts(),

    so put the below code in theme’s functions.php file.

    function count_user_posts_by_type( $userid, $post_type = 'post' ) {
        global $wpdb;
        $where = get_posts_by_author_sql( $post_type, true, $userid );
        $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
        return apply_filters( 'get_usernumposts', $count, $userid );
    }
    

    Now this function would take user id and post_type as parameter post_type='post' being the default and gets the count of post for that user for the concerned post_type

    You can verify it by echoing the below where you need to check the post count by the user.

    $user_posts = count_user_posts_by_type( 1, 'page' );
    echo $user_posts; // This would return the post count for user id 1 and post_type page.
    

    You can do the same for the custom post type. Now you need to get the user ids and pass through this function and display the name of the authors having 1 or more posts
    or

    You can add the below code where you want to display the list of users with one or more post

    $blogusers = get_users();
    foreach ( $blogusers as $user ) {
        if ( count_user_posts_by_type( $user->ID, 'post') ) {
             echo $user->user_nicename . '</br>';
        }
    }
    

    The above code lists all the users with one or more posts published of post_type post.

  2. Very old query but still there are no direct methods to get all authors with at least one post of ‘custom post type’. WP_User_Query also does not support the post type. Using $wpdb will solve the issue.

    Code:

    $post_type = 'gutentor';/*Your Post type*/
    global $wpdb;
    
    $all_authors = $wpdb->get_results(
        "
        select
    A.*, COUNT(*) as post_count
    from
    $wpdb->users A
    inner join $wpdb->posts B
    on A.ID = B.post_author
    WHERE ( ( B.post_type = '$post_type' AND ( B.post_status = 'publish' OR B.post_status = 'private' ) ) )
    GROUP BY A.ID
    ORDER BY post_count DESC"
    );
    
    if ( $all_authors ) {
        foreach ( $all_authors as $author) {
            echo $author->display_name;
        }
    }
    

    You just need to assign $post_type with your post type.

Comments are closed.