Post count for users by custom post type

This function shows the users postCPT count for each custom post type – similar to the dashboard box ‘at a glance’. You can see it at USERS -> ALL USERS. Instead of the default postcount there are now all custom post types listed and the user’s count for each of it.

/**
 * Snippet Name: Post count for users by custom post type
 * Snippet URL: https://www.wpcustoms.net/snippets/post-count-users-custom-post-type/
 */
  // unset the default posts table and create a new table "user_contributions"

function wpc_manage_users_columns($column_headers)
  {
  unset($column_headers['posts']);
  $column_headers['user_contributions'] = 'User Posts';
  return $column_headers;
  }

add_action('manage_users_columns', 'wpc_manage_users_columns');

// call our function for non-standard columns and connect our counting function 'wpc_get_author_post_type_counts'

add_action('manage_users_custom_column', 'wpc_manage_users_custom_column', 10, 3);

function wpc_manage_users_custom_column($custom_column, $column_name, $user_id)
  {
  if ($column_name == 'user_contributions')
    {
    $counts = wpc_get_author_post_type_counts();
    $custom_column = array();
    if (isset($counts[$user_id]) && is_array($counts[$user_id]))
    foreach($counts[$user_id] as $count) $custom_column[] = "t{$count['label']}" . "{$count['count']}";
    $custom_column = implode("n", $custom_column);
    }

  if (empty($custom_column)) $custom_column = "No contribution yet.";
    else $custom_column = "
n{$custom_column}n

“;
return $custom_column;
}

// grab posts and list run through each users post count displaying all custom post types

function wpc_get_author_post_type_counts()
{
static $counts;
if (!isset($counts))
{
global $wpdb;
global $wp_post_types;
$sql = posts}
WHERE 1=1
AND post_type NOT IN (‘revision’,’nav_menu_item’)
AND post_status IN (‘publish’,’pending’)
GROUP BY
post_type,
post_author
SQL;
$posts = $wpdb->get_results($sql);
foreach($posts as $post)
{
$post_type_object = $wp_post_types[$post_type = $post->post_type];
if (!empty($post_type_object->label)) $label = $post_type_object->label;
else
if (!empty($post_type_object->labels->name)) $label = $post_type_object->labels->name;
else $label = ucfirst(str_replace(array(
‘-‘,
‘_’
) , ‘ ‘, $post_type));
if (!isset($counts[$post_author = $post->post_author])) $counts[$post_author] = array();
$counts[$post_author][] = array(
‘label’ => $label,
‘count’ => $post->post_count,
);
}
}

return $counts;
}

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x