So far in this series, we’ve covered two separate ways to dismiss persistent WordPress admin notices. We’ll build on that in this fourth and final part of the tutorial series by looking at two more specific methods to permanently dismiss your admin notices. We’ll round things off by showing how to create your own custom admin notice types and add decorations such as icons.
Sticky Admin Notice
We already know how to display an admin notice that can be dismissed. All we have to do is add the is-dismissible
CSS class to the containing div element. However, this is only temporary and will only dismiss the notice for the current page. As soon as the page reloads, it reappears again.
To make it permanently dismissible involves more code than we’ve seen so far, but it isn’t too difficult to implement. Let’s take a look at what’s involved, starting with an overview.
We’ll use a custom option to store the display status of our admin notice. On plugin activation, this option will be created/updated and set to true. The admin notice will then only display if the option is currently true.
The key to this method is using Ajax to allow us to set the option to false when the dismiss button is clicked. Once successfully set to false, the conditional code that checks the option status will fail, and the admin notice will no longer be displayed.
Let’s begin by adding the admin notice itself, which will be a plain notice to begin. In Gwyer_Dismissible_Admin_Notices::init()
, add a new add_action
call:
add_action( 'admin_notices', array( $this, 'dismiss_admin_notice' ) );
Then add the dismiss_admin_notice()
callback function to the same class:
public function dismiss_admin_notice() { $whitelist_admin_pages = array( 'settings_page_admin-notices/plugin-options' ); $admin_page = get_current_screen(); if( in_array( $admin_page->base, $whitelist_admin_pages ) ) : ?>Dismiss me, if you can. Ha ha ha!
This adds an admin notice that displays only on the plugin admin page and is very similar to what we've seen in previous tutorials. The only slight difference here is that we've also added a CSS ID to the admin notice
div
container. This will be used to specifically target the admin notice we're interested in.We'll need to add JavaScript code to make the Ajax call work, so add a
js
folder in the rootadmin-notices
plugin folder and inside create a file calledadmin-notices.js
. Add code to the new file to test it's loading properly by outputting a console message.jQuery(document).ready(function($) { console.log( 'admin-notices.js loaded!' ); });In
Gwyer_Plugin_Options::init()
, add a newadd_action
call to enqueue our script file:add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );We only want this JavaScript file to be loaded on the plugin options page, so we need a way to conditionally enqueue it. We can do this by checking what admin page we're currently on to see if it's our plugin options page.
We can get a handle to our plugin options page by storing the return value of
add_options_page()
in a class property. We had no need of this value previously, so we just calledadd_options_page()
without storing the return value.Add a class property to
Gwyer_Plugin_Options
:protected $plugin_options_page;Then, in
create_admin_menu_page()
, use this new property to store the handle to our plugin options page:public function create_admin_menu_page() { $this->plugin_options_page = add_options_page( 'Admin Notices', 'Admin Notices', 'manage_options', __FILE__, array( $this, 'render_options_page' ) ); }We can finally enqueue our JavaScript file so that it loads only on the plugin options page:
public function enqueue_scripts($hook) { if( $hook != $this->plugin_options_page ) { return; } wp_enqueue_script( 'gwyer-admin-notice-js', plugin_dir_url( __FILE__ ) . 'js/admin-notices.js' ); }If all went well then you'll see an admin-notices.js loaded! message outputted to the browser console.
Update the JavaScript code in
admin-notices.php
to the following:jQuery(document).ready(function($) { $(document).on('click', '#an1 .notice-dismiss', function( event ) { data = { action : 'display_dismissible_admin_notice', }; $.post(ajaxurl, data, function (response) { console.log(response, 'DONE!'); }); }); });Here, we're listening for a click event on the
an1
CSS ID we added to our admin notice earlier. As soon as it's clicked, an Ajax request is fired. Let's handle that request next.In
Gwyer_Dismissible_Admin_Notices::init()
, add a newadd_action
call:add_action( 'wp_ajax_display_dismissible_admin_notice', array( &$this, 'display_dismissible_admin_notice' ) );This will run the callback function once the
display_dismissible_admin_notice
Ajax request fires. Remember that this originally was defined as thedata.action
property in our Ajax request.Now add the
display_dismissible_admin_notice
callback function toGwyer_Dismissible_Admin_Notices
:public function display_dismissible_admin_notice() { echo "Processing Ajax request..."; wp_die(); }Save your changes, reload the plugin options page, and click the admin notice dismiss button to see the Ajax request in action!
If the request was successful then you'll see a Processing Ajax request... DONE! message displayed in the browser console.
The final piece of the puzzle is to create a custom option initially set to true but which is then set to false when the dismiss button is clicked. Then, when the plugin options page loads, the admin notice only displays if the custom option value is true.
In
Gwyer_Dismissible_Admin_Notices::init()
, add a second call toregister_activation_hook()
:register_activation_hook( plugin_dir_path( __FILE__ ) . 'admin-notices.php', array( $this, 'create_custom_option' ) );And add the
create_custom_option
callback function to the class:public function create_custom_option() { update_option( 'gwyer-dismiss', true ); }Now, when the plugin is activated, a custom option called
gwyer-dismiss
is created and set totrue
.Update
display_dismissible_admin_notice()
to update our custom option when the Ajax request fires:public function display_dismissible_admin_notice() { update_option( 'gwyer-dismiss', false ); wp_die(); }Now all that's left to do is update
dismiss_admin_notice()
to check for the value of the custom option and only render the admin notice if it is set to true.public function dismiss_admin_notice() { $whitelist_admin_pages = array( 'settings_page_admin-notices/plugin-options' ); $admin_page = get_current_screen(); $display_status = get_option( 'gwyer-dismiss' ); if( in_array( $admin_page->base, $whitelist_admin_pages ) && $display_status ) : ?>Dismiss me, if you can. Ha ha ha!
Deactivate and reactivate the plugin to test the code we've added. Visit the plugin options page, dismiss the admin notice, and refresh the page. The notice should no longer be visible. Yay!
Because the custom option is set to true every time the plugin is activated, you can repeat the above steps to test the dismissible admin notice as many times as you like.
To keep things simple, this was a bare-bones example of using an Ajax request to set the custom admin notice option. In practice, you'd want to use a nonce (number used once) value to validate the Ajax request as a minimum security measure.
This was a lot of work to just permanently dismiss an admin notice, but the final effect works well and is something you can use to good effect in your own plugins.
Custom Action Admin Notice Dismissal
It's time to look at a slightly different method for dismissing admin notices now. This is a nag type of admin notice that displays on all admin screens and can't be dismissed until some action has been performed.
Note: Use this method with caution or you'll risk alienating your plugin users very quickly!
The specific action we'll focus on in our example will be to display an admin notice until a required plugin or list of plugins have been installed and activated.
Unlike the previous method where we had to jump through hoops to get an admin notice to be permanently dismissible, the solution for this method is refreshingly simple!
First, comment out all the function calls in
Gwyer_Dismissible_Admin_Notices::init()
. Then, add a newadd_action()
function:add_action( 'admin_notices', array( $this, 'install_plugin_to_dismiss_admin_notice' ) );And define the callback as follows:
public function install_plugin_to_dismiss_admin_notice() { if ( ! is_plugin_active( 'hello-dolly/hello.php' ) ) : ?>Please install and activate the Hello Dolly plugin.
That's all there is to it! I told you it was simple, didn't I?
The only thing we did differently this time was to use the
is_plugin_active()
WordPress function to test if the Hello Dolly plugin is installed and activated. If not,is_plugin_active()
will return false, and our admin notice will be displayed.Try activating the Hello Dolly plugin to verify the admin notice goes away.
This works well for single plugins, but what if you wanted to remind users to activate multiple plugins? Instead of hard-coding in the Hello Dolly plugin information, we could create an array to whitelist our required plugins.
Replace
install_plugin_to_dismiss_admin_notice()
with:public function install_plugin_to_dismiss_admin_notice() { $required_plugins = array( 'Hello Dolly' => 'hello-dolly/hello.php', 'Akismet' => 'akismet/akismet.php' ); $requires_activating = array(); foreach( $required_plugins as $required_plugin_name => $required_plugin_path ) { if( ! is_plugin_active( $required_plugin_path ) ) { array_push( $requires_activating, $required_plugin_name ); } } if ( ! empty( $requires_activating ) ) : ?>Please install and activate the following plugins: .
The required plugins are now stored in an array which is looped over to check if each plugin has been activated. For any plugin not currently active, the name is added to a
$requires_activating
array which is outputted via the admin notice as a comma-separated list of required plugin names.Custom Admin Notices
Before we finish, let's have a little fun by creating our own custom admin notice types. Let's see how to add some custom admin notice types of our own. By now you'll be fully familiar with the four built-in admin notices WordPress provides by default, but it's not that difficult to come up with some of our own.
First, though, comment out all function calls in
Gwyer_Dismissible_Admin_Notices::init()
so we start out on a clean slate.We'll need to add CSS for our custom admin notice types, so in the root plugin folder add a
css
folder, and inside create a file calledadmin-notices.css
. To enqueue it on all admin pages, add a newadd_action
call inGwyer_Plugin_Options::init()
.add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_styles' ) );Then, for the
enqueue_styles()
callback, add this method to the same class:public function enqueue_styles() { wp_enqueue_style( 'gwyer-admin-notice-css', plugin_dir_url( __FILE__ ) . 'css/admin-notices.css' ); }Now let's set up a new method to output our custom admin notices. In
Gwyer_Admin_Notices::init()
, add:add_action( 'admin_notices', array( $this, 'custom_admin_notices' ) );Then add a callback to display a series of custom admin notices:
/** * Output custom admin notices. */ public function custom_admin_notices() { ?>Houston, I definitely think we have a problem!
Congratulations, you've won the Admin user of the year award!
Now this is a great idea.
Join Neo and follow the white rabbit. If you see him give him this carrot. The rabbit that is, not Neo!
Finally, add CSS to
admin-notices.css
to style our custom admin notices:.notice-big-error { border: 3px solid red; -webkit-transform: rotateZ(-1deg); -ms-transform: rotateZ(-1deg); transform: rotateZ(-1deg); } .notice-admin-user-award { border-left: 5px solid purple; } .notice-admin-user-award p:before { font: normal 24px/1 'dashicons'; content: "f313"; color: purple; } .notice-light-bulb { border-right: 5px solid #e2e224; } .notice-light-bulb p:before { font: normal 22px/1 'dashicons'; content: "f339"; color: #e6e610; } .notice-social-media { border-left: 5px solid #1da25f; padding-bottom: 5px; } .notice-social-media p { padding-bottom: 0; margin-bottom: 4px; } .notice-social-media:after { font: normal 22px/1 'dashicons'; content: "f301 f304 f462"; color: #888; } .notice-neo { border-right: 10px solid orangered; border-left: 10px solid orangered; } .notice-neo p:before { font: normal 22px/1 'dashicons'; content: "f511"; color: orangered; }After you save the changes, load any admin page to see our custom admin notices.
Judging by the results, it's probably a good idea to use custom admin notices sparingly, otherwise you'll run the risk of them looking garish.
I won't go into details about the custom CSS used. It's just for a bit of fun, and most of the styling is pretty self-explanatory.
We used dashicons font icons for our custom admin notices for convenience as they are available in the WordPress admin by default. But you could import and use any icons you like for extra decoration.
Try the Code for Yourself
All the code from this tutorial series has been wrapped up in a WordPress plugin for you to download. Take a look at the code, extend it, and implement new ways to display (and dismiss) admin notices. Be sure to let me know in the comments if you create something cool! I'd love to see what you come up with.
Conclusion
Thank you for joining me in this four-part tutorial series. Hopefully you'll now have a lot more confidence in how you implement admin notices in your own projects.
We've covered many different aspects of WordPress admin notices, including multiple ways of permanently dismissing them, which isn't possible without custom code.
Creating your own custom admin notices is pretty easy too, but in practice you'd want to use them sparingly in your own projects. Most of the time it's best to keep to the default WordPress styles for a consistent user experience.
WordPress has an incredibly active economy. There are themes, plugins, libraries, and many other products that help you build out your site and project. The open-source nature of the platform also makes it a great option from which you can better your programming skills. Whatever the case, you can see what we have available in the Envato Market.
And don't forget to download the plugin and play around with the code. It's a great way to get more familiar with how all the pieces fit together. And please let me know your thoughts on the tutorial via the comments below.
Powered by WPeMatico