When a plugin adds one or more custom post types (CPTs), a nice little addition is to give post type counts of the entries on the dashboard, as a summary, where the number of posts and pages is already listed. Doing it for one CPT is easy enough; doing it for multiple CPTs is an obvious case for re-using code, and doing it for CPTs across multiple plugins makes a case for a separate library. Enter Gamajo Dashboard Glancer.
Show Post Type Counts With The Gamajo Dashboard Glancer Library
The Gamajo Dashboard Glancer project centres around a single class, Gamajo_Dashboard_Glancer, which can be included within your CPT plugin. You then instantiate this class, and register post types to it, when you want to show the counts.
| <?php | |
| // Require the new class (change to your correct path) | |
| if ( ! class_exists( 'Gamajo_Dashboard_Glancer' ) ) { | |
| require plugin_dir_path( 'includes/class-gamajo-dashboard-glancer.php' ); | |
| } | |
| // Hook into the widget (or any hook before it!) to register your items. | |
| add_action( 'dashboard_glance_items', 'prefix_add_dashboard_counts' ); | |
| function prefix_add_dashboard_counts() { | |
| $glancer = new Gamajo_Dashboard_Glancer; | |
| $glancer->add( 'my_cpt' ); // show only published "my-cpt" entries | |
| } |
See the project README for more code examples.
The class supports adding multiple CPTs at once, along with multiple statuses, including custom statuses, so there’s a lot of flexibility. The output becomes a list item, and will be linked, if the current user has the capability to edit entries.
The project also includes a second class that extends the first, to provide the appropriate markup for the table-based markup of the Right Now dashboard widget for WordPress 3.7 and earlier.
| <?php | |
| // Require the new class (change to your correct path) | |
| if ( ! class_exists( 'Gamajo_Dashboard_Glancer' ) ) { | |
| require plugin_dir_path( 'includes/class-gamajo-dashboard-glancer.php' ); | |
| require plugin_dir_path( 'includes/class-gamajo-dashboard-rightnow.php' ); | |
| } | |
| // WP 3.8 and later | |
| add_action( 'dashboard_glance_items', 'prefix_add_dashboard_counts' ); | |
| function prefix_add_dashboard_counts() { | |
| $post_types = array( 'mp_ingredient', 'mp_recipe', 'mp_mealplan' ); | |
| $statuses = array( 'publish', 'draft' ); | |
| $glancer = new Gamajo_Dashboard_Glancer; | |
| $glancer->add( $post_types, $statuses ); | |
| } | |
| // WP 3.7 and earlier | |
| add_action( 'right_now_content_table_end', 'prefix_add_dashboard_counts_old' ); | |
| function prefix_add_dashboard_counts_old() { | |
| $post_types = array( 'mp_ingredient', 'mp_recipe', 'mp_mealplan' ); | |
| $statuses = array( 'publish', 'draft' ); | |
| $glancer = new Gamajo_Dashboard_RightNow; | |
| $glancer->add( $post_types, $statuses ); | |
| } |
With a small bit of styling (not included within the class), you can make your CPT icons appear next to the counts as well:

Leave a Reply