I am using the code below to display all authors and their posts (in a custom post type called "publication"). This works, however it also lists users who do not have posts. How can I adapt this code to only show authors who have posts?
Thank you!
<h1>Articles by Author</h1>
<?php
$allUsers = get_users('orderby=title&order=ASC&post_type=publication');
$users = array();
// Remove subscribers from the list as they won't write any articles
foreach($allUsers as $currentUser)
{
if(!in_array( 'subscriber', $currentUser->roles ))
{
$users[] = $currentUser;
}
}
?>
<?php foreach($users as $user) { ?>
<div class="authorInfo">
<h2 class="authorName"><?php echo $user->display_name; ?></h2>
<?php query_posts( array( 'post_type' => 'publication', 'showposts' => -1, 'author'=>$user->ID ) ); while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<?php } ?>
UPDATE: Using the function from the answer below and a few things I read last night, here's what I have now (still not working as requested above, but wanted to give you my most recent code):
<?php
// count number of Articles (CPT) written by a user
function count_user_posts_by_type( $userid, $post_type = 'publication' ) {
global $wpdb;
$where = get_posts_by_author_sql( $post_type, true, $userid );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return $count;
$post_count = count_user_posts_by_type($userid, $post_type);
$allUsers = get_users('orderby=title&order=ASC&post_type=publication&role=author');
$users = array();
// CONDITIONAL -- IS THIS CORRECT?
if ($post_count > 0 ) {
// Remove subscribers from the list as they won't write any articles
foreach($allUsers as $currentUser)
{
if(!in_array( 'subscriber', $currentUser->roles ))
{
$users[] = $currentUser;
}
}
foreach($users as $user) { ?>
<h2 class="authorName"><?php echo $user->display_name; ?></h2>
<?php query_posts( array( 'post_type' => 'publication', 'showposts' => -1, 'author'=>$user->ID, 'orderby' => 'date', 'order' => 'DESC' ) );
while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php } } ?>