How to stop showing admin notice after close button has been clicked

Two ways to handle this.

a. Attach a timer to the notice:

You could attach a 3-second timer (or however long you wish) to the notice, as follows:

<?php
set_transient( "my-plugin", "alive", 3 );
add_action( 'admin_notices', function() {
   //Syntax correction
    if ( "alive" == get_transient( "my-plugin" ) ) {
        ?>
        <div class="notice notice-success is-dismissible">
            <p><?php _e( 'Imagine something here!', 'sample-text-domain' ); ?></p>
        </div>
        <?php
        delete_transient( "my-plugin" );
    }
});

After 3 seconds the transient expires and any future calls to the admin_notices hooked function will not display the notice. Should be enough time to allow the notice to display on the first page refresh after your plugin install completes. You can play with the timer, as needed.

b. Keep a history of the dismissal of the notice, with your own dismiss action:

function my_plugin_notice() {
    $user_id = get_current_user_id();
    if ( !get_user_meta( $user_id, 'my_plugin_notice_dismissed' ) ) 
        echo '<div class="notice"><p>' . _e( 'Imagine something here!', 'sample-text-domain' ) . '</p><a href="?my-plugin-dismissed">Dismiss</a></div>';
}
add_action( 'admin_notices', 'my_plugin_notice' );
    
function my_plugin_notice_dismissed() {
    $user_id = get_current_user_id();
    if ( isset( $_GET['my-plugin-dismissed'] ) )
        add_user_meta( $user_id, 'my_plugin_notice_dismissed', 'true', true );
}
add_action( 'admin_init', 'my_plugin_notice_dismissed' );

Once dismissed, the user meta is updated with that information, and the admin_notices hooked function will check for this and will only display the message if not true.

Leave a Comment