Better way to add a WordPress admin menu notification bubble

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.

admin menu bubble example

During the development of Posterno, I needed to add a notification bubble to the listings post type menu so that it would show the number of listings pending review.

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.

Because I’m building a plugin that is publicly distributed, I don’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 I’m 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.