How to list users that have written custom post types and hide the ones that have not?

I’m trying to build an author list that would show all authors that have written a Custom Post Type post, and hide authors that have no posts. With wp_list_authors it would be easy to show users that have written Posts (not CPT).

This does not show the users that have published Custom Post Types, it affects only to Posts.

Read More
wp_list_authors('hide_empty=1');

I looked in to the get_users function but managed to only build a list with it (more control over the list but not what I was aiming for).

 $blog_url = get_bloginfo('home');
 $blogusers = get_users('orderby=display_name&role=editor');
 foreach ($blogusers as $user) {
    echo '<li><a href="' . $blog_url . '/author/' . $user->user_login . '">' . $user->display_name . '</a></li>';
  }

I found this really nice post dealing with how to show the post counts in the backend. It defines a function _yoursite_get_author_post_type_counts() that could possibly maybe be some help in this…

Any idea how to do this? Thanks! 🙂

Related posts

Leave a Reply

1 comment

  1. wp_list_authors(), internally gets posts that are only of type post. See line 294 http://core.trac.wordpress.org/browser/tags/3.2.1/wp-includes/author-template.php#L273

    As you have noted, this answer is great and with some modification can do what you want.

    function wpse31443_author_has_custom_post_type( $post_author, $post_type ) {
        global $wp_post_types; // If nonexistent post type found return
        if ( array_intersect((array)$post_type, array_keys($wp_post_types))
            != (array)$post_type ) return false;
    
        static $posts = NULL; // Cache the query internally
        if ( !$posts ) {
            global $wpdb;
    
            $sql = "SELECT `post_type`, `post_author`, COUNT(*) AS `post_count`".
                " FROM {$wpdb->posts}".
                " WHERE `post_type` NOT IN ('revision', 'nav_menu_item')".
                " AND `post_status` IN ('publish', 'pending')".
                " GROUP BY `post_type`, `post_author`";
    
            $posts = $wpdb->get_results( $sql );
        }
    
        foreach( $posts as $post ) {
            if ( $post->post_author == $post_author
                and in_array( $post->post_type, (array)$post_type )
                and $post->post_count ) return true;
        }
    
        return false;
    }
    

    You already know how to get_users, so it should be a piece of cake to setup a simple foreach loop and feed the user IDs into your new function.

    I’ve tested the function to some extent, it should work as is, but may require some tweaking. Let me know if you have any questions and/or how I can improve my answer.