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

First of all I do know how to add admin notice in the wordpress admin menu. And I added an admin notice like this:

<?php
add_action( 'admin_notices', function() {
    ?>
    <div class="notice notice-success is-dismissible">
        <p><?php _e( 'Imagine something here!', 'sample-text-domain' ); ?></p>
    </div>
    <?php
});

Now my code is running fine and smooth, just with one problem.

You see right now this notice starts showing up as soon as the user activates the plugin. and it stays up top until the user click on the close button.

Now when the user click on any other admin page the notice starts showing up again.

What I want:

I want this notice to show up for all those are installing the plugin for the first time or updated to the latest version of my plugin.

But once the user clicks on the close button, it will not show up ever again, no matter which page the user goes.

I did google search about it but didn’t find any helpful answer, I hope you guys can help me out here.

Solutions Collecting From Web of "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() {
    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.