Adding Custom Admin Notices & Error alert in WordPress

When developing plugins for WordPress, I seldom use the Settings API to build the plugin settings page instead, I build it from ground-up utilizing the Options API to store the plugin data to the database.

Not quite long, I discovered I could use the function add_settings_error() — a member of the Settings API family — to output custom admin notices/messages to users about settings validation problems, missing settings and even success notice.

To output an error notice, use the function like so:


add_settings_error( 'settings-page-slug', 'error_code', 'Error message to display' );

To output a notice that denotes success, add the string update as the fourth function parameter like so:


add_settings_error( 'settings-page-slug', 'error_code', 'Success message to display', 'updated' );

To add custom CSS classes to the notice div container, include a space separated class name as the fourth parameter.

Say you want to add the hello, hi as well as the updated class name to the div container, see the code below:


add_settings_error( 'settings-page-slug', 'error_code', 'Success message to display', 'updated hello hi' );

Note: I discovered the notice won’t show up in the plugin custom settings page unless you add the function settings_errors() where you want the notice to display (preferably below the <h1> settings page title).

Using Admin Notices Action Hook

You can also use the admin_notices Action to output notices like so:


function my_admin_notice() {
    ?>
    <div class="updated">
        <p><?php _e( 'Updated!', 'text-domain' ); ?></p>
    </div>
    <?php
}
add_action( 'admin_notices', 'my_admin_notice' );

The difference between using this and the add_settings_error() are:

* With add_settings_error(), you won’t have to include the notice HTML markup.

* You won’t have to include settings_errors() for the notice to display if you use admin_notices as this is automatically done by the hook.

Don’t miss out!
Subscribe to My Newsletter
Invalid email address