Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created November 26, 2018 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/a7b10e37c4128913e4069f2825a443cd to your computer and use it in GitHub Desktop.
Save tommcfarlin/a7b10e37c4128913e4069f2825a443cd to your computer and use it in GitHub Desktop.
[WordPress] A Helper Function for Admin Notices
<?php
/**
* Provides an easy eay to display an administration notice based on the incoming
* class and message.
*
* @param string $class the class to add to the notice (warning, error, success)
* @param string $message the message to display in the administration notice area
*/
protected function displayAdminNotice($class, $message)
{
add_action(
'admin_notices',
function () use ($class, $message) {
printf(
'<div class="%1$s"><p>%2$s</p></div>',
esc_attr($class),
esc_html($message)
);
}
);
}
<?php
if (!$this->hasValidInput()) {
$this->displayAdminNotice(
'notice notice-error',
'You must specify a valid email address and license key.'
);
}
<?php
if (update_option('acme-option', $values)) {
$this->displayAdminNotice(
'notice notice-success',
'The options were updated successfully!'
);
}
@senlin
Copy link

senlin commented Nov 30, 2018

Couldn't find a comment box on the post itself. Great tip!

I think it would have been even better if you'd have internationalised the output?

@tommcfarlin
Copy link
Author

@senlin

I have comments disabled on the blog, but you're on point with internationalization. I opt not to include it because it's out of scope of the content of the post but it's not something that should be ignored.

And it's something that I'm eventually going to cover more in-depth (though I have some resources already though it's a couple of years old).

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