Instructor Lead On-Demand Learning Courses - Learning Extravaganza All Pro Web Designs and Udemy are happy to offer this special to you. Act Now!

Persisted WordPress Admin Notices: Part 4

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.

Instructor Lead On-Demand Learning Courses All Pro Web Designs and Udemy are happy to offer this special to you. Act Now!

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!

< ?php endif; }

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 root admin-notices plugin folder and inside create a file called admin-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 new add_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 called add_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.

Admin notice JavaScript loaded

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 new add_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 the data.action property in our Ajax request.

Now add the display_dismissible_admin_notice callback function to Gwyer_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!

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 to register_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 to true.

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!

< ?php endif; }

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 new add_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.

< ?php endif; }

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.

Example of a nag admin notice

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: < ?php echo join( ", ", $requires_activating );?>.

< ?php endif; }

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.

List of required plugins

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 called admin-notices.css. To enqueue it on all admin pages, add a new add_action call in Gwyer_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.

Let's connect!

Join Neo and follow the white rabbit. If you see him give him this carrot. The rabbit that is, not Neo!

< ?php }

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.

See more from Net Tuts
Instructor Lead On-Demand Learning Courses All Pro Web Designs and Udemy are happy to offer this special to you. Act Now!

Leave a Reply