How to code dismissable status dialog in your plugin

You may experience many specific situations when you develop your wordpress plugin or theme. One of them is when you need to show admin notice dialog to the user with dismiss button. Actually I’m talking about the wordpress action you can fire with admin_notices hook. Some of you may say this is a quite common situation, but the special part of this is the dismiss button. So when the user clicks the button he/she wants to avoid to see the same dialog next time. That makes sense.

admin_dialog

So how to do that ? I’ll describe that here and show you the code how to do that.

  1. I use add_action function to call admin_notices wordpress action hook
  2. The action will call the function which uses get_user_meta function to check if the dismiss button was already clicked or not
  3. If it was not clicked before it will show the dialog. If it was, it will skip the function.
  4. The dialogs’ dismiss button contains GET parameter in the query string and I use it in admin_init hook next time the page is loaded. Actually this GET parameter indicates to me that the dismiss button has been clicked.
  5. In admin_init hook I check for that specific GET parameter and if it’s present I’ll use add_user_meta to save the information to DB

Here is the code:

function aboutme3000_show_message()
{
    $user_id = get_current_user_id();
    if ( ! get_user_meta($user_id, 'aboutme3000_nag_ignore') ) {
        $msg = "You need to upgrade your database as soon as possible...";
        echo '<div id="message" class="updated fade"><p>';
        echo ('<b>About Me 3000 Plugin notice</b>: Structure of the Social links changed. Please check your links on the <a href="/wp-admin/options-general.php?page=About-Me">settings</a> page');
        echo "</p>";
        echo "<p><strong><a class=\"dismiss-notice\" href=\"options-general.php?page=About-Me&aboutme3000_nag_ignore=0\" target=\"_parent\">Dismiss this notice</a></strong></p></div>";
    }
}

function aboutme3000_init()
{
    if ( isset($_GET['aboutme3000_nag_ignore']) && '0' == $_GET['aboutme3000_nag_ignore'] ) {
        $user_id = get_current_user_id();
        add_user_meta($user_id, 'aboutme3000_nag_ignore', 'true', true);
        if (wp_get_referer()) {
            /* Redirects user to where they were before */
            wp_safe_redirect(wp_get_referer());
        } else {
            /* if there is no referrer you redirect to home */
            wp_safe_redirect(home_url());
        }
    }
}


add_action('admin_notices', 'aboutme3000_show_message');
add_action('admin_init', 'aboutme3000_init');
2 Comments
  1. March 18, 2018
    • May 21, 2018

Leave a Reply

Your email address will not be published. Required fields are marked *