4elements

blog

Persisted WordPress Admin Notices: Part 3

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:

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 if settings-updated is set to true.

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.

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.

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:

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():

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.

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 the register_activation_hook() and add_action() function calls. Now let's set up a basic admin notice which we'll extend the functionality of shortly.

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:

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 $counterbefore 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 to display_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:

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.

To use the new reset feature, simply change $counter_reset to true 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.