Using WordPress ‘get_settings_errors()’ PHP function

The get_settings_errors() WordPress PHP function fetches settings errors registered by add_settings_error() during the current page load.

Usage

get_settings_errors( string $setting = '', bool $sanitize = false );

Example:

Input:

get_settings_errors( 'my_custom_setting', true );

Output:

Array of settings errors.

Parameters

  • $setting (string, optional): Slug title of a specific setting whose errors you want. Default: ”.
  • $sanitize (bool, optional): Whether to re-sanitize the setting value before returning errors. Default: false.

More information

See WordPress Developer Resources: get_settings_errors()

Examples

Display Errors for All Settings

Display settings errors for all settings registered.

What the code does:

function display_all_settings_errors() {
    $settings_errors = get_settings_errors();

    if ( ! empty( $settings_errors ) ) {
        foreach ( $settings_errors as $error ) {
            echo '<div class="' . $error['type'] . '"><p><strong>' . $error['message'] . '</strong></p></div>';
        }
    }
}
add_action( 'admin_notices', 'display_all_settings_errors' );

Display Errors for a Specific Setting

Display settings errors for a specific setting called ‘my_custom_setting’.

What the code does:

function display_specific_setting_errors() {
    $setting = 'my_custom_setting';
    $settings_errors = get_settings_errors( $setting );

    if ( ! empty( $settings_errors ) ) {
        foreach ( $settings_errors as $error ) {
            echo '<div class="' . $error['type'] . '"><p><strong>' . $error['message'] . '</strong></p></div>';
        }
    }
}
add_action( 'admin_notices', 'display_specific_setting_errors' );

Add and Display a Custom Error

Add a custom error and display it using get_settings_errors().

What the code does:

function add_and_display_custom_error() {
    add_settings_error( 'my_custom_setting', 'custom_error', 'This is a custom error!', 'error' );
    $settings_errors = get_settings_errors( 'my_custom_setting' );

    if ( ! empty( $settings_errors ) ) {
        foreach ( $settings_errors as $error ) {
            echo '<div class="' . $error['type'] . '"><p><strong>' . $error['message'] . '</strong></p></div>';
        }
    }
}
add_action( 'admin_notices', 'add_and_display_custom_error' );

Add and Display a Custom Notice

Add a custom notice and display it using get_settings_errors().

What the code does:

function add_and_display_custom_notice() {
    add_settings_error( 'my_custom_setting', 'custom_notice', 'This is a custom notice!', 'updated' );
    $settings_errors = get_settings_errors( 'my_custom_setting' );

    if ( ! empty( $settings_errors ) ) {
        foreach ( $settings_errors as $error ) {
            echo '<div class="' . $error['type'] . '"><p><strong>' . $error['message'] . '</strong></p></div>';
        }
    }
}
add_action( 'admin_notices', 'add_and_display_custom_notice' );