Julien Liabeuf

Easy Dismissible Notices in WordPress

April 02, 2016 | 2 Minute Read | No Comments

WordPress admin notices are great. They're extremely handy for communicating an important message to the users of your theme or plugin.

A WordPress Admin Notice

Admin notices can be used for sharing an information, warning of a problem, etc. WordPress made is very easy to register with the admin_notices hook. There is one extremely important thing though: admin notice dismissal.

Dismiss an Admin Notice

Have you ever used a plugin that displays a notice that can't be dismissed? Or a notice that comes back on every page load, whether or not you have dismissed it already? What a pain... Nobody wants that.

In WordPress 4.2, WordPress introduced dismissible admin notices. This is basically a front-end mechanism that hides a notice when you click the close button. But again, refresh the page and the notice is back.

Persistent Notices Dismissal

What you want is for a notice to be permanently dismissed once this close button is clicked. This is exactly what WP Dismissible Notices Handler does.

WP Dismissible Notices Handler on GitHub
WP Dismissible Notices Handler on GitHub

After writing admin notices dismissal functions over and over I realize how dumb I was for not having a re-usable library. So much for DRY heh.

So I wrote this one. You can very easily use it in your projects using Composer:

composer require julien731/wp-dismissible-notices-handler

This library does 2 things:

  1. Register admin notices
  2. Handle dismissal

Where this library differs from other libraries you can find is the options. When registering a notice, there are two important things that you can set:

  • A user capability: for the notice to show up only for users with a specific capability. Very handy to show a message for admins only for instance.
  • A scope: you decide if the notice should be dismissed at the user level (dismissed for the current user but still on for other users) or at the site level (one user dismisses it for everyone else)

How easy is it to use this library? Well, it's just one function call away.

dnh_register_notice( 'my_notice', 'updated', __( 'This is my notice' ) );

That's it. With this one line of code you just registered an admin notice that can be properly dismissed. Find all the available parameters on the GitHub repository.

Leave a Comment