Easy Dismissible Notices in WordPress
WordPress admin notices are great. They're extremely handy for communicating an important message to the users of your theme or plugin.
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.
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:
This library does 2 things:
- Register admin notices
- 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.
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.