Since WordPress 4.6 it is relatively simple to add validation to customize settings, to give helpful error messages to the user. Here I show you how that works.
There are three ways to add validation:
- By defining a
validate_callback
when registering a setting. - By using the
sanitize_callback
of a setting. - By creating a custom
validate
method of theWP_Customize_Setting
class.
This post describes the second way – you can find examples and more information about the topic in the post »Customizer APIs in 4.6 for Setting Validation and Notifications« by Weston Ruter.
That is, for example, the sanitize function for checking the value of a select field that contains all categories of the WordPress site:
/**
* Select sanitization callback for categories select control.
*
* @param string $input Value of select field.
*
* @return string
*/
function hannover_sanitize_categories_select( $input ) {
$can_validate = method_exists( 'WP_Customize_Setting', 'validate' );
$term = get_term( $input );
if ( 'category' !== $term->taxonomy || is_wp_error( $term ) || null === $term ) {
return $can_validate ? new WP_Error( 'nan', __( 'The ID does not match a category.', 'hannover' ) ) : null;
}
return $input;
}
Code language: PHP (php)
To display a specific error message, we can return a WP_Error
object to which we pass an error code as the first parameter and the error message as the second. However, this behavior does not work until WordPress 4.6, so we first check whether the validate
method of the WP_Customize_Setting
class exists.
Afterwards, we check if the input is a category and in case of an error we return either a specific error message (in WordPress 4.6 and later) or null
if we are dealing with an older version. In this case, the user would receive a general error message that the value is invalid. If everything is okay, we return the input value.
Displaying of the error message looks like that (takes a while after changing the value, while the preview refreshes):