Displaying Author’s Custom Post Type Count on Admin Panel

By default, WordPress would display the Posts count of any user from the “Users” admin panel. Now, what about the Custom Post Type? In one of my previous post, I already explained how to register a custom post type in WordPress. If I were to assume that you have a custom post type registered on your site, you might also be interested to see which user wrote/contributed how many custom posts.

Today, in this post I will try to explain how can you create a custom column on Users admin panel and then display the custom post type count for any user. So, let’s get started.

The very first thing we need to do is to create a custom column on users admin panel. We can easily do that using the following functions that uses “manage_users_columns” filter.

<?php
function ib_add_books_column($columns){
   $columns['cpt_books'] = 'Books';
   return $columns; }
add_filter('manage_users_columns','ib_add_books_column');
?>

Now, one might ask, what if I have multiple post type and I want to add multiple column? Well in that case we can easily create another custom column simply by adding the following line:

$columns['cpt_name'] = 'Display Name';

At this point, we are done with adding custom column. However, in order to display the post count (posts written by any user), we need to create another function to retrieve the post count against any give user ID from the database. This is how you can do it.

<?php
function ib_books_post_count($val,$column_name,$user_id){
   $user = get_userdata($user_id);
   global $post;
   switch ($column_name) { 
      case 'cpt_books' : return count( get_posts( array(
         'post_type' => 'books', 
         'author' => $user_id,
         'nopaging' => true,)));
      break; default: }	
   return $return; }
add_filter('manage_users_custom_column','ib_books_post_count', 10, 3);
?>

At the very beginning of this function we declared “global $post” for the post object and “$user” variable to hold the user ID. Later on, I used Switch statement to associate with the column name from previous function and then using get_posts with our desired parameter to display the post count.

These are fairly simple and easy to use functions. I hope you found this post to be useful. Now, taking your questions.

Today In History

  •  
  •  

Comment

2 Comments

  1. EdwinPublished: 3 years ago

    Thanks this helped me!

  2. IftekharPublished: 3 years ago

    Happy to know 🙂

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from Postable, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.