Created
January 8, 2020 14:21
-
-
Save nfsarmento/b62c7b588f143f1a6532c9b2f88ed418 to your computer and use it in GitHub Desktop.
Custom Post(s) Type Counts WordPress Admin Column on User List Page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action('manage_users_columns','ns_manage_users_columns'); | |
function ns_manage_users_columns($column_headers) { | |
unset($column_headers['posts']); | |
$column_headers['custom_posts'] = 'Posts'; | |
return $column_headers; | |
} | |
add_action('manage_users_custom_column','ns_manage_users_custom_column',10,3); | |
function ns_manage_users_custom_column($custom_column,$column_name,$user_id) { | |
if ($column_name=='custom_posts') { | |
$counts = ns_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 style='padding:0'>{$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 ns_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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment