Skip to content

Instantly share code, notes, and snippets.

@jterry
Last active December 16, 2015 17:08
Show Gist options
  • Save jterry/5467753 to your computer and use it in GitHub Desktop.
Save jterry/5467753 to your computer and use it in GitHub Desktop.
Simple WP function to insert admin notices and errors.
/**
* Include
* add_action('admin_notices', 'lm_admin_message');
* in your setup, then call
* lm_admin_message('error', 'the message, fool!'); or
* lm_admin_message('notice', 'the notice, fool!');
* to display the admin message.
*
* @param string|null $type Supports "error" and "notice" (or null if it's the setup hook call)
* @param string|null $message Body of your message (or null if it's the setup hook call)
*/
function lm_admin_message($type = null, $message = null) {
if(!is_admin())
return;
if(empty($type) && empty($message)) {
if(!function_exists('display')) {
function display($type, $messages) {
if(!empty($messages) && is_array($messages)) {
$o = '<div class="' . $type . '">';
foreach($messages as $message)
$o .= '<p>' . $message . '</p>';
echo $o . '</div>';
}
}
}
if(!empty($_GET['lm_errors'])) {
$errors = get_option('lm_errors');
display('error', $errors);
delete_option('lm_errors');
}
if(!empty($_GET['lm_notices'])) {
$notices = get_option('lm_notices');
display('updated', $notices);
delete_option('lm_notices');
}
return;
}
switch($type) {
case 'error': $type = 'errors'; break;
case 'notice': $type = 'notices'; break;
default: return; break;
}
$items = get_option('lm_' . $type);
if(!$items)
$items = array();
update_option('lm_' . $type, array_merge($items, array( $message )));
add_filter('redirect_post_location', 'redirect_post_location_' . $type);
if(!function_exists('redirect_post_location_errors')) {
function redirect_post_location_errors($loc) {
return add_query_arg('lm_errors', 1, remove_query_arg('message', $loc));
}
}
if(!function_exists('redirect_post_location_notices')) {
function redirect_post_location_notices($loc) {
return add_query_arg('lm_notices', 1, remove_query_arg('message', $loc));
}
}
}
@jterry
Copy link
Author

jterry commented Apr 26, 2013

Might also want to mark the post as a draft, if you used this to show a user errors in their input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment