How to Create Admin Notice On Plugin Activation

plugin-activation-notice-example

Adding admin notice on plugin activation can be super useful. For example we can:

  • Add link to the settings page,
  • Giving info about minimum requirement of their server,
  • Tutorial links,
  • Promote pro version of our plugin,
  • Ask the user to rate our plugin,
  • Ask donation,
  • Or simply telling them that they are awesome.

If you ever try to create an “Admin Notice” on plugin activation. You’ll know that using admin_notices action inside your “activation hook function” will not work. But there’s a workaround for that.

What I mean above is a code like this will not work:

/* Register activation hook. */
register_activation_hook( __FILE__, 'my_plugin_activation_hook' );

/**
 * Runs only when the plugin is activated.
 * @since 0.1.0
 */
function my_plugin_activation_hook() {
    /* Add admin notice */
    add_action( 'admin_notices', 'my_plugin_activation_notice' );
}

/**
 * Admin Notice on Activation.
 * @since 0.1.0
 */
function my_plugin_activation_notice(){
    ?>
    <div class="updated notice is-dismissible">
        <p>Thank you for using this plugin! <strong>You are awesome</strong>.</p>
    </div>
    <?php
}

The Solution

There’s several ways to do this. But it’s basically the same. We need to save temporary data on plugin activation, check that data, if the data available display notice and delete it.

If it’s a temporary data, the best way to save that is using WP Transient API.

It’s pretty straight forward. Here’s the full code and plugin example:

/* Register activation hook. */
register_activation_hook( __FILE__, 'fx_admin_notice_example_activation_hook' );

/**
 * Runs only when the plugin is activated.
 * @since 0.1.0
 */
function fx_admin_notice_example_activation_hook() {

    /* Create transient data */
    set_transient( 'fx-admin-notice-example', true, 5 );
}


/* Add admin notice */
add_action( 'admin_notices', 'fx_admin_notice_example_notice' );


/**
 * Admin Notice on Activation.
 * @since 0.1.0
 */
function fx_admin_notice_example_notice(){

    /* Check transient, if available display notice */
    if( get_transient( 'fx-admin-notice-example' ) ){
        ?>
        <div class="updated notice is-dismissible">
            <p>Thank you for using this plugin! <strong>You are awesome</strong>.</p>
        </div>
        <?php
        /* Delete transient, only display this notice once. */
        delete_transient( 'fx-admin-notice-example' );
    }
}

Useful! Right?

1 Comment

  1. Omer

    Just implemented your exact code in my plugin but it didn’t work for me.

Comments are closed.