How to add a notification bubble to the WordPress admin menu

How to add a notification bubble to the WordPress admin menu

Alessandro Tesoro

27 Dec 2022

You've probably seen the small notification bubble that shows up in the Dashboard menu when a new update is available. In WordPress, notification bubbles alongside the menu name are displayed when there are comments pending approval or plugins that require an update, just to name a few.

With a quick Google search you can easily find the solution in a matter minutes. A common issue with the code in those articles is that they all assume you know the position of your menu item isn’t going to change and so, they attach the bubble html markup by using a fixed array key.

But what if you're building a plugin that is publicly distributed? You wouldn't necessarily know what the user's website look like. They might have used a plugin that changes the position of dashboard menu items. The only thing that we're sure of is the URL. So we're going to use the URL to find the position of our custom menu item.

With the help of the wp_list_filter() function we're going to find the position of our menu items by filtering the array via the URL. In my case the url is edit.php?post_type=listings then we use the key() function to get the array key of the menu item and finally modify the item's name and merge it with the html markup of the bubble.

1function pno_show_pending_listings_count_bubble() {
2
3 global $menu;
4
5 $pending_count = '5';
6
7 $listings_menu_item = wp_list_filter( $menu, [ 2 => 'edit.php?post_type=listings' ] );
8
9 if ( ! empty( $listings_menu_item ) && is_array( $listings_menu_item ) ) {
10 $menu[ key( $listings_menu_item ) ][0] .= " <span class='awaiting-mod update-plugins count-" . esc_attr( $pending_count ) . "'><span class='pending-count'>" . absint( number_format_i18n( $pending_count ) ) . '</span></span>';
11 }
12}
13add_action( 'admin_menu', 'pno_show_pending_listings_count_bubble' );

Taking it further

The above code is going to be executed on every admin page load and it might slow the website down if the count involves some intensive database operation.

You can make use of the WordPress transients API to cache the count for a set period of time. Just remember to delete the transient at the appropriate time.