How to show the number of custom post type items in At a Glance
I recently moved all my plugin announcement posts to a custom post type called Announcements. This allows me to keep my blog posts focussed on some awesome WordPress tutorials that I am writing. So, do subscribe to my newsletter to receive them directly in your inbox!
By default, the number of posts from a custom post type doesn’t show up in the At a Glance widget in the WordPress dashboard. I also find that an easy way to navigate to custom post types.
Here’s a custom snippet I use in my mu-plugins folder to display the number of announcements.
/**
* Add the number of posts from a Custom Post Type to the At a Glance widget.
*
* @param array $items Array of items.
* @return array Updated array of items
*/
function wzn_dashboard_glance_items( $items ) {
// Set the array of post types to display.
$post_types = array( 'announcements' );
foreach ( $post_types as $cpt ) {
$cpt_info = get_post_type_object( $cpt );
$num_posts = wp_count_posts( $cpt );
$num = absint( $num_posts->publish + $num_posts->private );
if ( $num ) {
$text = _n( $cpt_info->labels->singular_name, $cpt_info->labels->name, $num ); // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralSingle,WordPress.WP.I18n.NonSingularStringLiteralPlural
$num = number_format_i18n( $num );
if ( current_user_can( 'edit_posts' ) ) {
$text = '<a class="page-count ' . esc_attr( $cpt_info->name ) . '-count" href="edit.php?post_type=' . esc_attr( $cpt ) . '">' . $num . ' ' . $text . '</a>';
} else {
$text = sprintf( '<span class="page-count">%1$s</span>', $text );
}
$items[] = $text;
}
}
return $items;
}
add_filter( 'dashboard_glance_items', 'wzn_dashboard_glance_items', 1 );
You can also pass an array of post types to $post_types
in Line 10 above. I use that for a custom plugin I’ve built using ACF that has multiple custom post types.
The result is an updated At a Glance widget which now shows the number of announcements.
Customise the Icon
By default, a circular icon is displayed, as you can see in the screenshot above. But, if you’d like, you can replace this with any other icon. I like using Dashicons and had picked the megaphone when registering my custom post type.
This code will allow you to add CSS to the admin_head
. Change \f488
to the code of the dashicon of your choosing.
/**
* Add CSS to Admin head
*/
function wzn_admin_head() {
?>
<style type="text/css" media="screen">
#dashboard_right_now .announcements-count:before {
content: "\f488";
}
</style>
<?php
}
add_filter( 'admin_head', 'wzn_admin_head' );
Like this tutorial? Let me know what you think!