1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
<?php
namespace SIW\Admin;
class Notices {
protected $transient_name;
protected $types = [
'success',
'info',
'warning',
'error'
];
public function __construct() {
$this->set_transient_name();
}
protected function set_transient_name() {
$this->transient_name = 'siw_admin_notices_' . get_current_user_id();
}
public static function init() {
$self = new self();
add_action( 'admin_notices', [ $self, 'display_notices' ] );
}
public function display_notices() {
$notices = $this->get_notices();
if ( false == $notices ) {
return;
}
foreach ( $notices as $notice ) {
$dismissable = ( $notice['dismissable'] ) ? ' is-dismissible' : '';
?>
<div class="notice notice-<?= esc_attr( $notice['type'] ); ?> <?= esc_attr( $dismissable );?>">
<p><?= esc_html( $notice['message'] ); ?></p>
</div>
<?php
}
$this->clear_notices();
}
public function add_notice( string $type, string $message, bool $dismissable = false ) {
$type = in_array( $type, $this->types ) ? $type : 'info';
$notices = $this->get_notices();
$notices[] = [
'type' => $type,
'message' => $message,
'dismissable' => $dismissable,
];
$this->set_notices( $notices );
}
protected function clear_notices() {
delete_transient( $this->transient_name );
}
protected function get_notices() {
return get_transient( $this->transient_name );
}
protected function set_notices( array $notices ) {
set_transient( $this->transient_name, $notices, 60 );
}
}