Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show message after activating WordPress plugin

I want to display an activation message after activating the plugin.

I've seen a few questions on SO about this, but none of 'em work properly:

if (!get_option("startup")) {
    echo "<div class='updated'><h3>Welcome to [name]</h3>";
    update_option('startup', 'true');
}

That works.. kinda. It puts the HTML at the very top, even before the <!DOCTYPE>. Is there any way to put it at the right place? So in the body tag?

like image 495
J. Doe Avatar asked Jul 06 '16 21:07

J. Doe


1 Answers

There's a few things you'll need to do here. Firstly, the register_activation_hook() function is used to hook into the activation of your plugin. And the admin_notices action is used to add a notice inside the admin area (you can't just print your notice out anywhere).

However, there's an additional complication in that you can't use the admin_notices action on plugin activation. This is because WordPress doesn't 'live activate' your plugin - it activates it in the background and suppresses the output in order to make sure, before completing the activation, that it doesn't trigger any fatal errors.

Fortunately, this blog post outlines a solution to this problem. The author of the post suggests using transients to save the 'state' of your plugin so that it can be retrieved once it has been activated.

Because that blog has a CC-BY-SA license like this site, I'll copy the code in here so it lives on. I've slightly condensed it to keep the length of this post down, but you can view the whole blog post for the full solution. I've also tested this to ensure it still works - and it does on my install of WordPress 4.5.3.

register_activation_hook( __FILE__, 'fx_admin_notice_example_activation_hook' );

function fx_admin_notice_example_activation_hook() {
    set_transient( 'fx-admin-notice-example', true, 5 );
}

add_action( 'admin_notices', 'fx_admin_notice_example_notice' );

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' );
    }
}
like image 97
Tim Malone Avatar answered Nov 15 '22 13:11

Tim Malone