Displaying “One Time” Notification in Plugins

The idea is that you need to save_errors or update the option that has the errors/notices whenever you want. As soon as its output once by admin_notices it will be cleared.

/**
 * Sample_Notice_Handling
 */
class Sample_Notice_Handling {

    public static $_notices  = array();

    /**
     * Constructor
     */
    public function __construct() {

        add_action( 'admin_notices', array( $this, 'output_errors' ) );
        add_action( 'shutdown', array( $this, 'save_errors' ) );
    }

    /**
     * Add an error message
     */
    public static function add_error( $text ) {
        self::$_notices[] = $text;
    }

    /**
     * Save errors to an option
     */
    public function save_errors() {
        update_option( 'custom_notices', self::$_notices );
    }

    /**
     * Show any stored error messages
     */
    public function output_errors() {
        $errors = maybe_unserialize( get_option( 'custom_notices' ) );

        if ( ! empty( $errors ) ) {

            echo '<div id="mc_errors" class="error notice is-dismissible">';

            foreach ( $errors as $error ) {
                echo '<p>' . wp_kses_post( $error ) . '</p>';
            }

            echo '</div>';

            // Clear
            delete_option( 'custom_notices' );
        }
    }

}

tech