WordPress admin notices as flash notice using transient API to display after page reload.
By default WordPress doesn't provide a solution to show admin notices after page reload. Frameworks lik CodeIgniter does have a flash message feature. Using which, you can show one time notices across user interface. With this simple library you can make use of WordPress' transient API and show one time admin notices like a flash message.
You can install this library using composer
composer require duckdev/wp-flash-notices
Or, you can download latest version of the library from releases tab.
- PHP 5.4+
- WordPress 4.0+
Import the library class and assign custom namespace.
use DuckDev\WP_Flash_Notices as My_Custom_Notices;
Create new instance of the notices class with our custom transient name.
$notices = new My_Custom_Notices( 'my-custom-notices' );
There are 4 types of notices.
Notice with green bar.
// Register new success notice to the queue.
$notices->add( 'custom-success', 'This is a custom success notice.', 'success' );
Notice with red bar.
// Register new error notice to the queue.
$notices->add( 'custom-error', 'This is a custom error notice.', 'error' );
Notice with yellow bar.
// Register new warning notice to the queue.
$notices->add( 'custom-warning', 'This is a custom warning notice.', 'warning' );
Notice with blue bar.
// Register new info notice to the queue.
$notices->add( 'custom-info', 'This is a custom info notice.', 'info' );
Show a dismiss button in notice.
// Register new info notice to the queue.
$notices->add( 'custom-success', 'This is a custom dismissible notice.', 'success', true );
By default all notices are shown within single site admin screens. If you have Multisite you can add network admin notices by setting last argument as true:
// Register new info notice to the queue.
$notices->add( 'custom-success', 'This is a custom dismissible notice.', 'success', true, true );
If you'd like to print the notices in the front-end, then use the below action to your template.
do_action('front_notices');