Skip to content

Instantly share code, notes, and snippets.

@obenland
Last active October 31, 2016 12:10
Show Gist options
  • Save obenland/5173811 to your computer and use it in GitHub Desktop.
Save obenland/5173811 to your computer and use it in GitHub Desktop.
<?php
// Can be called whenever.
function add_admin_notice( $code, $message, $type = 'error' ) {
global $wp_admin_notices;
if ( ! isset( $wp_admin_notices ) )
$wp_admin_notices = array();
$wp_admin_notices[] = array(
'code' => $code,
'message' => $message,
'type' => $type,
);
}
// Gets called once, after the 'all_admin_notices' hook.
function do_admin_notices() {
if ( defined( 'DOING_AJAX') && DOING_AJAX )
return;
global $wp_admin_notices;
if ( ! isset( $wp_admin_notices ) )
return;
foreach ( $wp_admin_notices as $notice ) {
printf( '<div id="setting-error-%1$s" class="%2$s settings-error"><p>%3$s</p></div>',
$notice['code'],
$notice['type'],
$notice['message']
);
}
unset( $GLOBALS['wp_admin_notices'] );
}
// Save all notices on shutdown.
function save_admin_notices() {
global $wp_admin_notices;
if ( isset( $wp_admin_notices ) )
set_transient( 'admin-notices-' . get_current_user_id(), $wp_admin_notices, 30 );
}
add_action( 'shutdown', 'save_admin_notices' );
// Load all notices on init
function load_admin_notices() {
if ( false !== $notices = get_transient( 'admin-notices-' . get_current_user_id() ) ) {
global $wp_admin_notices;
if ( ! isset( $wp_admin_notices ) )
$wp_admin_notices = array();
$wp_admin_notices = array_merge( $wp_admin_notices, $notices );
delete_transient( 'admin-notices-' . get_current_user_id() );
}
}
add_filter( 'admin_init', 'load_admin_notices' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment