Web Development by Solarise

The Solarise.dev Blog

Add your own custom admin notifications to the wp-admin WordPress dashboard

Blog archive Robin Metcalfe 26th November 2017

When working on a theme or plugin for WordPress which relies on custom user interactions, it’s helpful to be able to provide clear and concise feedback to your users.

Sometimes users don’t notice errors or warning notices at all!

Download the code for this article

Although overly intrusive notifications can be a hinderance, it’s sometimes useful to give users a friendly nudge in the right direction.

WordPress has admin notification built in as standard, but it can be a little cumbersome to properly set up and the default notifications aren’t always as visible as you might like for providing proper feedback.

” />

In this article, I outline a solution which makes use of WordPress’ transients functionality as well as some additional javascript to add some visual flair (completely optional).

Adding user notifications into your code

First, we’ll add a custom helper function to our code (wherever you like, whether in your plugin or theme’s functions.php file)

This function (custom_notification_helper()) will act as the helper function you can call throughout your own code to easily insert a notification message. E.g. custom_notification_helper('Oh no! Something went wrong', 'error');) will insert an error message into the notification heap.

/**
 * Our custom notification helper function. Use this to add messages to the 
 * notifications heap during execution of your theme/function code
 */
function custom_notification_helper($message, $type)
{

    if(!is_admin()) {
        return false;
    }

    // todo: check these are valid
    if(!in_array($type, array('error', 'info', 'success', 'warning'))) {
        return false;
    }

    // Store/retrieve a transient associated with the current logged in user
    $transientName = 'admin_custom_notification_'.get_current_user_id();

    // Check if this transient already exists. We can use this to add
    // multiple notifications during a single pass through our code
    $notifications = get_transient($transientName);

    if(!$notifications) {
        $notifications = array(); // initialise as a blank array
    }

    $notifications[] = array(
        'message' => $message,
        'type' => $type
    );

    set_transient($transientName, $notifications);  // no need to provide an expiration, will
                                                    // be removed immediately

}

This function (custom_admin_notice_handler) is responsible for printing admin notices in the appropriate section on the WordPress admin page. You can print anything you like at this stage, it’s not a particularly elegant hook, but for our purposes, we’ll print out a series of <div> elements with the appropriate class names for each of the WordPress notification types (which are ‘info’, ‘success’, ‘error’ and ‘warning’)

/**
 * The handler to output our admin notification messages
 */
function custom_admin_notice_handler() {

    if(!is_admin()) {
        // Only process this when in admin context
        return;
    }

    $transientName = 'admin_custom_notification_'.get_current_user_id();

    // Check if there are any notices stored
    $notifications = get_transient($transientName);

    if($notifications):
        foreach($notifications as $notification):
            echo <<<HTML

                <div class="notice notice-custom notice-{$notification['type']} is-dismissible">
                    <p>{$notification['message']}</p>
                </div>

HTML;
        endforeach;
    endif;

    // Clear away our transient data, it's not needed any more
    delete_transient($transientName);

}
add_action( 'admin_notices', 'custom_admin_notice_handler' );

Testing

Finally, a little test function (test_custom_admin_notices) that’ll let you see the above in action easily. To see this, visit e.g. http://yoursite.com/wp-admin/?test_admin_notices – the page will redirect to the admin dashboard, and you should see four different notification messages pop up.

/**
 * A simple little function to help test this functionality. Call
 * e.g. http://yoursite.com/wp-admin/?test_admin_notices to check
 * if this is working
 */
function test_custom_admin_notices()
{
    if(isset($_GET['test_admin_notices'])) {
        custom_notification_helper('Custom error notice', 'error');
        custom_notification_helper('Custom success notice', 'success');
        custom_notification_helper('Custom warning notice', 'warning');
        custom_notification_helper('Custom info notice', 'info');
        // Simulate a redirect
        header('Location: index.php');
        exit;
    }
}
add_action('admin_init', 'test_custom_admin_notices');

Remove this code before using the code on a production site. It wouldn’t cause any harm leaving it in, but it’s nice to keep things tidy.

Adding some custom animation

Sometimes you might want to make your notifications a little more visible to the end user. I’m not usually a fan of making significant adjustments to an existing platform’s user interface, but in the case of WordPress, I think it’s reasonable to make small tweaks here and there. When done with care, minor adjustments to an interface’s UI can be effective.

We’ll implement a simple "wiggle" effect upon creation of an "error" notification to make it clear to a user that something has gone wrong which needs attention. We’ll also add a less noticeable wiggle to the "warning" state

Here’s the animation in action.

animated display of notification transitions

This won’t loop continuously on the admin dashboard. It’ll play once, then stop. The animation in the gif is for demonstration purposes. A constantly buzzing admin notification would be irritating!

Here, we’ll make use of CSS keyframes to define a series of animations which will give the notifications a little "kick", and make them slightly more noticeable to the user. Tweak these as required (or don’t use them at all!) – they’re useful if you need to e.g. make it very obvious to an administrator of your site that a particular error has occurred, or otherwise need to increase the visibility of errors.

Please these into your theme’s functions.php file

add_action('admin_head', 'add_notification_styling');
function add_notification_styling()
{
    echo <<<HTML
    <style>

        @keyframes custom-notification-wiggle {
          10%, 90% {
            transform: translate3d(-1px, 0, 0);
          }

          20%, 80% {
            transform: translate3d(2px, 0, 0);
          }

          30%, 50%, 70% {
            transform: translate3d(-4px, 0, 0);
          }

          40%, 60% {
            transform: translate3d(4px, 0, 0);
          }
        }

        .notice-custom.notice-error.active-wiggle {
            animation: custom-notification-wiggle 0.5s cubic-bezier(0.645, 0.045, 0.355, 1) both;
        }

        .notice-custom.notice-warning.active-wiggle {
            animation: custom-notification-wiggle 0.25s cubic-bezier(0.645, 0.045, 0.355, 1) both;
        }

    </style>
HTML;
}

(Note that we could easily add this into a custom CSS file, but for ease of use, it’s normally quicker just to drop custom styling straight into the admin layout)

And additionally, some extra Javascript code to initialise the active-wiggle state of the notices.

add_action('admin_head', 'add_notification_scripting');
function add_notification_scripting()
{
    echo <<<HTML
    <script type='text/javascript'>

        jQuery(function($){
            $('.notice-custom.notice-error, .notice-custom.notice-warning').addClass('active-wiggle');
        });

    </script>
HTML;
}

(Again, rather than setting up a seperate javascript file for the admin area, we’re just dropping the script directly into the <head> of the page)

Using animation for all WordPress notifications

Note that the above code will only apply to the notice-custom elements we’ve introduced through our previous code snippet. If you’d like this to apply to all WordPress notifications, simply remove the .notice-custom selector from the CSS rules anove.

So, there you have it. WordPress admin notifications made simple. Hopefully this will help you make your code’s behaviour more transparent to the end user.

Download the code for this article

Author Image

About the author

Robin is the dedicated developer behind Solarise.dev. With years of experience in web development, he's committed to delivering high-quality solutions and ensuring websites run smoothly. Always eager to learn and adapt to the ever-changing digital landscape, Robin believes in the power of collaboration and sharing knowledge. Outside of coding, he enjoys diving into tech news and exploring new tools in the industry.

If you'd like to get in touch to discuss a project, or if you'd just like to ask a question, fill in the form below.

Get in touch

Send me a message and I'll get back to you as soon as possible. Ask me about anything - web development, project proposals or just say hi!

Please enable JavaScript in your browser to complete this form.

Solarise.dev Services

Maintenance Retainers

Min 3 hours per month, no contract

Project Planning

Get in touch to discuss your project details

Consultancy

Face-to-face chats. Solve your problems!