Error Messages with WordPress Settings API

WordPress’ Settings API makes it fairly simple to display error messages or notices in the admin backend.

To let WordPress know that there is a message that you want to display, call the add_settings_error() function:

add_settings_error( $setting, $code, $message, $type );

This function adds your message to a queue of messages, linked to the slug provided with the first parameter. You can register multiple messages to one slug – they will be displayed underneath of each other. The second parameter specifies a unique error code, which will be added to the id attribute of the <div> holding the message (so make sure to sanitize it properly). Then you pass on the actual message (remember to always make strings translatable 😉 ).  And with the last parameter you can specify, whether it is an error message or a notice. The parameter defaults to ‘error’.

So lets add a notice message:

add_settings_error(
    'unique_identifyer',
    esc_attr('settings_updated'),
    __('Settings saved.'),
    'updated'
);

On every page load in the admin, the admin_notices hook fires, giving plugin and theme authors a possibility to add and display their messages. And here is how:

function unique_identifyer_admin_notices() {
     settings_errors( 'unique_identifyer' );
}
add_action( 'admin_notices', 'unique_identifyer_admin_notices' );

All parameters to the settings_errors function are optional, but since you probably only want to show your registered messages, you should specify the slug you used when adding the message.

And that’s all there is to it! Two simple functions to add and display error messages and notices in the admin area. Try it out and let me know what you think!

One thought on “Error Messages with WordPress Settings API

  1. Pingback: How to Display Notices and Errors using the Settings API : WPMayor

Leave a Reply