Admin Notice Helper That Survives Redirects
Adds a wpide_flash_notice() helper that queues a success, warning or error message for the current user and shows it on the next admin screen, even after a redirect.
Opens WPIDE on
Code
if ( ! function_exists( 'wpide_flash_notice' ) ) {
function wpide_flash_notice( $message, $type = 'success' ) {
$user_id = get_current_user_id();
if ( ! $user_id ) {
return;
}
$queue = (array) get_transient( 'wpide_flash_' . $user_id );
$queue[] = array( 'message' => (string) $message, 'type' => in_array( $type, array( 'success', 'warning', 'error', 'info' ), true ) ? $type : 'info' );
set_transient( 'wpide_flash_' . $user_id, array_filter( $queue ), 5 * MINUTE_IN_SECONDS );
}
}
add_action( 'admin_notices', function () {
$key = 'wpide_flash_' . get_current_user_id();
$queue = get_transient( $key );
if ( ! $queue ) {
return;
}
delete_transient( $key );
foreach ( (array) $queue as $notice ) {
printf( '<div class="notice notice-%s is-dismissible"><p>%s</p></div>', esc_attr( $notice['type'] ), wp_kses_post( $notice['message'] ) );
}
} );
Notes
Example wpide_flash_notice( 'Import finished.', 'success' ); before wp_safe_redirect(); messages are stored per user for five minutes.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.