Skip to content

Instantly share code, notes, and snippets.

@tnog
Created April 27, 2021 20:09
Show Gist options
  • Save tnog/1753dac6fc14e0997f90f878b8c06f3a to your computer and use it in GitHub Desktop.
Save tnog/1753dac6fc14e0997f90f878b8c06f3a to your computer and use it in GitHub Desktop.
<?php
namespace To4Framework;
if (!defined('ABSPATH')) {
exit;
}
/**
* Wrapper class to display admin and debug.log messages.
* To use, as an example for a success notifiction AdminNotice::displaySuccess($message)
* @see https://wordpress.stackexchange.com/questions/152033/how-to-add-an-admin-notice-upon-post-save-update
*/
class AdminNotice {
/**
* Static property to hold our singleton instance
*
*/
const NOTICE_FIELD = 'to4_admin_response';
/**
* Retrieve stored message from options and show in admin notices, also sends message to debug.log
* and clears 'to4_admin_response'options table field
* @uses admin_notices hook
* @return void
*/
public function displayAdminNotice()
{
$responses = get_option(self::NOTICE_FIELD, []);
if (!empty($responses)) {
foreach ( $responses as $response ) {
$message = esc_html( $response['message'] ); //isset($response['message']) ? $response['message'] : false;
$noticeLevel = ! empty($response['notice-level']) ? esc_attr( $response['notice-level'] ) : 'notice-error';
echo "<div class='notice {$noticeLevel} is-dismissible'><p>{$message}</p></div>";
}
}
// Now we reset our options to prevent notices being displayed forever.
if( !empty( $responses ) ) {
delete_option(self::NOTICE_FIELD, []);
}
}
/**
* Updates 'to4_admin_response' options field with message, and sets notice type to 'error'
* @param string $message
* @return void
*/
public static function displayError($message)
{
self::updateOption($message, 'notice-error');
}
public static function displayWarning($message)
{
self::updateOption($message, 'notice-warning');
}
public static function displayInfo($message)
{
self::updateOption($message, 'notice-info');
}
public static function displaySuccess($message)
{
self::updateOption($message, 'notice-success');
}
/**
* Store response message in options temporarily for display in admin_notices hook
* @param string $message
* @param string $noticeLevel
* @return void
*/
protected static function updateOption($message, $noticeLevel) {
$response = get_option( self::NOTICE_FIELD, [] );
// We add our new notice.
array_push( $response, [
'message' => sanitize_text_field($message),
'notice-level' => sanitize_text_field($noticeLevel),
] );
// Then we update the option with our notices array
update_option(self::NOTICE_FIELD, $response );
}
/**
* Prints a message to the debug file that can easily be called by any method.
* @param mixed $message an object, array, string, number, or other data to write to the debug log
*
*/
public static function log($message)
{
error_log(print_r($message, true));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment