Adds Post Counts by Post Type per User in the User List withing WordPress' Admin console (URL path => /wp-admin/users.php)

  • Download Gist
wp-post-counts-for-user-by-post-type.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
<?php
/*
Adds Post Counts by Post Type per User in the User List withing WordPress' Admin console (URL path => /wp-admin/users.php)
 
Written for: http://wordpress.stackexchange.com/questions/3233/showing-users-post-counts-by-custom-post-type-in-the-admins-user-list
By: Mike Schinkel (http://mikeschinkel.com)
Date: 24 October 2010
 
*/
 
add_action('manage_users_columns','yoursite_manage_users_columns');
function yoursite_manage_users_columns($column_headers) {
unset($column_headers['posts']);
$column_headers['custom_posts'] = 'Posts';
return $column_headers;
}
 
add_action('manage_users_custom_column','yoursite_manage_users_custom_column',10,3);
function yoursite_manage_users_custom_column($custom_column,$column_name,$user_id) {
if ($column_name=='custom_posts') {
$counts = _yoursite_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<tr><th>{$count['label']}</th>" .
"<td>{$count['count']}</td></tr>";
$custom_column = implode("\n",$custom_column);
if (empty($custom_column))
$custom_column = "<th>No Posts!</th>";
$custom_column = "<table>\n{$custom_column}\n</table>";
}
return $custom_column;
}
 
function _yoursite_get_author_post_type_counts() {
static $counts;
if (!isset($counts)) {
global $wpdb;
global $wp_post_types;
$sql = <<<SQL
SELECT
post_type,
post_author,
COUNT(*) AS post_count
FROM
{$wpdb->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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.