As we all know, the Settings API is fantastic for building plugin and theme options and settings pages.
There are countless tutorials about it, and we also highlighted some of the best ones in a recent post.
A plugin that uses this well is Soliloquy (a really robust slider plugin). Here’s a sample modeled on this plugin’s code:
[php]
function myplugin_admin_messages() {
if(isset($_GET[‘myplugin-message’]) && $_GET[‘myplugin-message’] == ‘discount_updated’) {
add_settings_error( ‘myplugin-notices’, ‘myplugin-discount-updated’, __(‘Discount code updated.’, ‘myplugin’), ‘updated’ );
}
if(isset($_GET[‘myplugin-message’]) && $_GET[‘myplugin-message’] == ‘discount_update_failed’) {
add_settings_error( ‘myplugin-notices’, ‘myplugin-discount-updated-fail’, __(‘There was a problem updating your discount code, please try again.’, ‘myplugin’), ‘error’ );
}
settings_errors( ‘myplugin-notices’ );
}
add_action(‘admin_notices’, ‘myplugin_admin_messages’);
[/php]
Thomas Griffin, the developer behind Soliloquy, presents three reasons for using the Settings API to output admin notices and errors:
- You ensure that your notices will remain consistent for any WordPress version, and
- You can register all your messages through one slug and output them with a simpleΒ
settings_errors()
Β call - You can use add_settings_error() anywhere before the admin_notices hook to register your messages, and since they are all registered through one slug, it makes it really easy to create new notices.
This StackExchange thread contains an excellent explanation, while Konstantin Kovshenin also makes reference to the display of notices and errors using the Settings API in his talk at WordCamp Bulgaria.
Here’s yet another code sample on how to use notices and errors in a simple way.
Codex reference:
https://codex.wordpress.org/Function_Reference/add_settings_error
https://codex.wordpress.org/Function_Reference/settings_errors
If you enjoyed this post, make sure to subscribe to WP Mayor’s RSS feed.