Skip to content

Instantly share code, notes, and snippets.

@wkw
Created August 1, 2016 20:29
Show Gist options
  • Save wkw/2011b4819b6875299c6b21d99a5fce54 to your computer and use it in GitHub Desktop.
Save wkw/2011b4819b6875299c6b21d99a5fce54 to your computer and use it in GitHub Desktop.
Reusable WordPress Admin Notices PHP class
<?php
/**
* source: http://wordpress.stackexchange.com/a/222027/3844
*
* USAGE:
* add_action('admin_notices', [AdminNotice::getInstance(), 'displayAdminNotice']);
* $notice = AdminNotice::getInstance();
* $notice->displayError(__('Better flee, an error occurred.', 'herp'));
*
*/
class AdminNotice
{
private static $instance;
const NOTICE_FIELD = 'derp_admin_notice_message';
protected function __construct() {}
private function __clone() {}
private function __wakeup() {}
static function getInstance()
{
if (null === static::$instance) {
static::$instance = new static();
}
return static::$instance;
}
public function displayAdminNotice()
{
$option = get_option(self::NOTICE_FIELD);
$message = isset($option['message']) ? $option['message'] : false;
$noticeLevel = ! empty($option['notice-level']) ? $option['notice-level'] : 'notice-error';
if ($message) {
echo "<div class='notice {$noticeLevel} is-dismissible'><p>{$message}</p></div>";
delete_option(self::NOTICE_FIELD);
}
}
public function displayError($message)
{
$this->updateOption($message, 'notice-error');
}
public function displayWarning($message)
{
$this->updateOption($message, 'notice-warning');
}
public function displayInfo($message)
{
$this->updateOption($message, 'notice-info');
}
public function displaySuccess($message)
{
$this->updateOption($message, 'notice-success');
}
protected function updateOption($message, $noticeLevel) {
update_option(self::NOTICE_FIELD, [
'message' => $message,
'notice-level' => $noticeLevel
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment