Google+
Shineyrock web design & consultancy

Shineyrock

blog

  • like 3 07

    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:

    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.

    When the plugin options page is loaded normally we don't see a value set for settings-updated.

    Normal Plugin Options Page Loading

    Now enter some text in the Enter some text field and click Save Changes. This time, we see settings-updated set to true, which we can put to good use.

    The settings-updated value set to true

    Replace the conditional_plugin_admin_notice with:

    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.

    A more personal admin notice message

    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.

    The final result when plugin options are saved is shown below.

    The finished admin notice to show the plugin has been updated

    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:

    In admin_notices.php, add another require_once() call to import our new class:

    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.

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

    Then, add the display_admin_notice callback function as a new class method:

    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 one-off admin notice

    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.

    Add a new add_action() call in init():

    And then flesh out the callback function display_admin_notice_counter():

    This will display a standard admin notice that will appear on every WordPress admin page.

    Standard admin notice ready for customisation

    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:

    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.

    Counter admin notice in action

    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 to display_admin_notice_counter() underneath the declaration for $counter:

    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.

    Display an additional message on the final render

    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 to 5 and add a new class property:

    Then, inside init() replace

    with

    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.

    To use the new reset feature, simply change $counter_reset to true and load any admin page.

    Reset admin notice counter

    Then change it back to false again.

    Admin notice counter successfully reset

    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.

    martijn broeders

    founder/ strategic creative at shineyrock web design & consultancy
    e-mail: .(JavaScript must be enabled to view this email address)
    phone: 434 210 0245

By - category

    By - date