I have added a setting field in the general settings page. The field and the validation work, but the validation error message does not show.
<?php
add_action( 'admin_init', 'initialize_extra_settings' );
function initialize_extra_settings() {
register_setting(
'general',
'setting_app_store_app_url',
array (
'type' => 'string',
'sanitize_callback' => 'settings_url_field_validation'
)
);
add_settings_field(
'app-store-app-url-field', // Field slug
'App Store app URL',
'app_store_app_url_field_cb',
'general', // In this settings page (slug)
'default', // In this section (slug)
array(
'label_for' => 'app-store-app-url-field',
'class' => 'custom-settings-row'
)
);
}
function app_store_app_url_field_cb( $args) {
$setting = get_option('setting_app_store_app_url');
?>
<input
id="<?php echo $args['label_for'];?>"
name="setting_app_store_app_url"
type="url"
value="<?php echo isset( $setting ) ? esc_attr( $setting ) : ''; ?>"
/>
<?php
}
function settings_url_field_validation( $value ) {
$urlRegExp = "/https:\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])/";
if ( !preg_match($urlRegExp, $value) ) {
add_settings_error( 'setting_app_store_app_url', 'invalid_app_store_app_url', 'Must be a valid url', 'error' );
return null;
}
return $value;
}
add_action( 'admin_notices', 'show_custom_settings_admin_notices' );
function show_custom_settings_admin_notices() {
var_dump(get_settings_errors('setting_app_store_app_url'));
settings_errors('setting_app_store_app_url');
}
The var_dump(get_settings_errors('setting_app_store_app_url'));
returns an empty array.
settings_errors()
because it is automatically called on that admin page (wp-admin → Settings → General), hence any validation errors would appear at the top of the page without one having to manually show them.settings_errors()
but nothing changes.Ctrl+u
on Chrome+Windows desktop) - do the error messages really not available anywhere in the source?