Welcome back to our series on persisted WordPress admin notices. We’re now in a good position to be able to extend our admin notice functionality and control when they appear on the page.
After that, we’ll move on to persistent admin notices and see how you can make sure they’re dismissed in such a way that they don’t reappear when admin pages are reloaded.
This is particularly important as custom admin notices implemented in plugins and themes are only really useful when you can permanently dismiss them. It’s not enough to simply add the is-dismissible
CSS class.
Controlling When Admin Notices Appear
Up until now, all admin notices have been displayed as soon as the page loads. There may be times when this is inconvenient and you want the admin notice to be displayed after a certain event has been triggered instead.
How about if we wanted a custom admin notice to be displayed on the plugin options page we created earlier, but only after the Save Changes button was clicked?
We already know from part two how to restrict an admin notice to the plugin options page. Let’s find out how we can trigger it to appear after plugin options have been saved.
Begin by commenting out the add_action
function call for plugin_admin_notice
. Then, add a fourth add_action
call in init
as follows:
add_action( 'admin_notices', array( $this, 'conditional_plugin_admin_notice' ) );
Whenever plugin options are saved, a settings-updated
value of true
is added to the super global $_GET
array variable. We can use this to determine if we need to display our admin notice.
Add a new conditional_plugin_admin_notice
method to Gwyer_Admin_Notices
that outputs the value of $_GET
to the screen.
/** * Output an admin notice on the plugin options page when settings have been saved. */ public function conditional_plugin_admin_notice() { echo ""; print_r($_GET); echo "";
}When the plugin options page is loaded normally we don’t see a value set for settings-updated.
Now enter some text in the Enter some text field and click Save Changes. This time, we see
settings-updated
set totrue
, which we can put to good use.Replace the
conditional_plugin_admin_notice
with:/** * Output an admin notice on the plugin options page when settings have been saved. */ public function conditional_plugin_admin_notice() { $whitelist_admin_pages = array( 'settings_page_admin-notices/plugin-options' ); $admin_page = get_current_screen(); $current_user = wp_get_current_user(); if( in_array( $admin_page->base, $whitelist_admin_pages ) && isset( $_GET[ 'settings-updated' ] ) && $_GET[ 'settings-updated' ] ): ?>Plugin options just saved. display_name; ?>, you're just so awesome!
By now, this code should be looking familiar to you. A couple of new features have been added, though. Firstly, the conditional expression has been extended to test for the presence of
settings-update
. Now, the admin notice will only display if we're on the plugin options page and ifsettings-updated
is set totrue
.Also, the current user display name is outputted to make the admin notice a little more personal.
The
wp_get_current_user()
function returns information about the currently logged-in user. This object is stored in$current_user
and contains details such as user email, ID, first name, last name, and display name, which is the particular property we're interested in.Finally, for a little extra polish, we've prevented the default admin notice from displaying so our custom one is the only one visible to the user. To achieve this, we just added a single line of code to
conditional_plugin_admin_notice()
to output CSS to hide the unwanted admin notice.echo "";The final result when plugin options are saved is shown below.
While this works fine for demonstration purposes, a better (and cleaner) approach would be to add styles to a separate style sheet instead and enqueue it on the plugin options page only.
Our custom admin notice could be extended even further in a number of ways. One possibility could be to maintain a log that stored the current date/time along with user information every time the plugin options were saved.
Or how about getting the admin notice to display how many times the plugin options have been saved that day, week, month, etc.? I'm sure you can think of more examples too!
Dismissing Persisted Admin Notices Effectively
It's time to get our hands dirty now and dig into more in-depth code as we turn our attention to dismissing persistent admin notices. Up until now, the only way we've seen how to do this is to add the
.is-dismissible
CSS class to our admin notice div container. This dismisses the admin notice for the current page, but it isn't much use in practice as it reappears when an admin page is reloaded.So how can we fix this? We'll look at several different methods of dismissing persistent admin notices, including:
- One-off admin notice that disappears after one view.
- An admin notice counter that disappears after a certain number of views.
- Sticky admin notice that remains dismissed upon page refresh.
- Custom action dismissal (admin notice removed after specific action has completed).
Before we start implementing each of these examples, make sure all add_action()
calls in Gwyer_Admin_Notices::init()
have been commented out. Then add a new dismissible-admin-notices.php
file to the admin_notices
plugin folder. Open up this new file and add a new class definition:
init();
In admin_notices.php
, add another require_once()
call to import our new class:
require_once(dirname(__FILE__) . '/dismissible-admin-notices.php' );
The Gwyer_Dismissible_Admin_Notices
class will contain all code related to dismissing persisted admin notices.
One-Off Admin Notice
The first method we'll look at is how to display an admin notice just the once so it doesn't reappear on page load. You could use this method to notify a user when a plugin or theme has just been activated.
Let's do this for our Admin Notices plugin. We'll start by registering a WordPress transient option upon plugin activation that's set to expire almost immediately.
In the Gwyer_Dismissible_Admin_Notices
class, add a call to register_activation_hook()
:
register_activation_hook( plugin_dir_path( __FILE__ ) . 'admin-notices.php', array( $this, 'set_admin_notice_transient' ) );
The register_activation_hook()
function requires you to specify the path to the main plugin file, but we're currently in dismissible-admin-notices.php
. So we can't just use the PHP magic constant __FILE__
we used previously as this always points to the current PHP file.
Instead, we have to build the path to the main plugin file ourselves using plugin_dir_path( __FILE__ ) . 'admin-notices.php'
.
When the Admin Notices plugin is activated, it will run code added to a set_admin_notice_transient
class method, which we'll define next.
public function set_admin_notice_transient() { set_transient( 'admin-notice-transient', true, 5 ); }
This method creates a new transient called 'admin-notice-transient'
with a value of true
, and is set to expire after five seconds.
Let's make use of this transient by conditionally displaying an admin notice if we're on the right admin page and our transient still exists.
Add a new add_action()
call to init()
.
add_action( 'admin_notices', array( &$this, 'display_admin_notice' ) );
Then, add the display_admin_notice
callback function as a new class method:
public function display_admin_notice() { $current_user = wp_get_current_user(); $whitelist_admin_pages = array( 'plugins' ); $admin_page = get_current_screen(); if( in_array( $admin_page->base, $whitelist_admin_pages ) && get_transient( 'admin-notice-transient' ) ) : ?>The Admin Notices plugin was just activated. Thanks for your support display_name; ?>!
Similarly to previous examples, the admin notice only displays if we are on a specific page—in this case, the main admin plugins page. But we have an additional condition that the
'admin-notice-transient'
must also exist, otherwise the admin notice won't display.After the admin notice is outputted, the transient is deleted immediately, even though we initially set it to expire after only five seconds. This just ensures that it won't be shown again. This could potentially happen if a user tried to refresh the plugins page very quickly. But by deliberately deleting the transient, we can be certain this won't ever be the case.
To test the code we just added, head on over to the main plugins page and deactivate, then reactivate, the Admin Notices plugin.
The key here is the
'admin-notice-transient'
transient setting. Without this, the admin notice would appear every time the plugins page loaded (after the plugin was activated), which isn't what we want.Admin Notice Counter
Next up is an admin notice that will display a set number of times only, after which it won't be visible anymore. Also, this time around it won't be restricted to any particular admin page.
Before we begin, in the
Gwyer_Dismissible_Admin_Notices
class, comment out theregister_activation_hook()
andadd_action()
function calls. Now let's set up a basic admin notice which we'll extend the functionality of shortly.Add a new
add_action()
call ininit()
:add_action( 'admin_notices', array( &$this, 'display_admin_notice_counter' ) );And then flesh out the callback function
display_admin_notice_counter()
:public function display_admin_notice_counter() { ?>Counter admin notice.
This will display a standard admin notice that will appear on every WordPress admin page.
Let's think about what we need to do. Our admin notice should display a set number of times, and each time it appears an internal counter is increased by one. Once the counter limit has been reached, the admin notice shouldn't appear again.
We want the admin notice to be displayed on any admin page and so the counter value must persist between page loads. One good way of doing this is to use a database option to store the counter value.
Add a counter class property to store the counter limit value:
public $counter_limit = 5;This will be used shortly to manage how many times the admin notice appears. Inside
display_admin_notice_counter()
, update the code as follows:public function display_admin_notice_counter() { $counter = get_option( 'admin_notice_counter', 1 ); ?>This admin notice has been displayed time(s).
Prior to the admin notice being displayed, we're retrieving the counter option, and a default value is returned if it doesn't yet exist. After the admin notice renders, the counter option is increased by one and updated. If it doesn't exist then a new option will be created to store the current value.
We've also updated the CSS class to be an information admin notice.
Try visiting various admin pages and see the counter increase each time.
The
++$counter
code is an example of a pre-increment operator. It adds a value to$counter
before it's saved to the database. If we used a post increment operator (i.e.$counter++
) then the value of$counter
would be stored first and then increased, which wouldn't work.Let's incorporate
$counter_limit
now to prevent the admin notice appearing too many times. Add this todisplay_admin_notice_counter()
underneath the declaration for$counter
:if( $counter > $this->counter_limit ) { return; }Now, once the admin notice has displayed five times, it won't be visible on subsequent admin pages. It might be nice, though, to display a message the last time the admin notice appears so the user knows it won't appear again. Extend the conditional expression and output an additional message:
public function display_admin_notice_counter() { $counter = get_option( 'admin_notice_counter', 1 ); if( $counter > $this->counter_limit ) { return; } else if( $counter == $this->counter_limit ) { $extra_message = " It's time to say goodbye now."; } ?>This admin notice has been displayed time(s).
However, you won't see the message if you've already gone over the counter limit. You can temporarily solve this by increasing the
$counter_limit
variable.For testing purposes, it would be better to be able to reset the counter limit. If you know how to edit the database, you can go in and change the option directly, but this can be tedious to do multiple times. So let's implement our own reset feature.
First, change
$counter_limit
back to5
and add a new class property:public $counter_reset = false;Then, inside
init()
replaceadd_action( 'admin_notices', array( &$this, 'display_admin_notice_counter' ) );with
$this->reset_counter_check();The reset function should either show our counter admin notice or delete the
admin_notice_counter
database option and display a warning admin notice instead.public function reset_counter_check() { if( !$this->counter_reset ) { add_action( 'admin_notices', array( &$this, 'display_admin_notice_counter' ) ); } else { delete_option( 'admin_notice_counter' ); ?>Admin notice counter has been reset! Change
$counter_reset
tofalse
to start the admin notice counter again.To use the new reset feature, simply change
$counter_reset
totrue
and load any admin page.Then change it back to
false
again.Note: This method could easily be used to display an admin notice just the once, as we did in the previous example, but it's slightly more complicated to set up. It really depends on your requirements.
If all you ever need is a single use admin notice then the previous method will probably suit your needs better and is quicker to implement. But the counter method is more flexible, and once set up, it's just as easy to use in your own projects.
Conclusion
We've covered quite a lot of ground in part three of this tutorial series. We've seen how to control when admin notices appear rather than just always appearing as soon as an admin page has finished loading. This is useful in many ways, but our example showed how to display a custom admin notice after plugin options had been saved.
Then, we moved on to two distinct examples of dismissing persistent admin notices. This gives you a lot of flexibility in how you present admin notices to the user. And in the next and final part of this tutorial series, we'll be looking at more ways to dismiss persistent admin notices.
And, for a bit of fun, we'll create our own custom admin notice types and add icon decorations.
Powered by WPeMatico