Validating customize settings with displaying error messages

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:

  1. By defining a validate_callback when registering a setting.
  2. By using the sanitize_callback of a setting.
  3. By creating a custom validate method of the WP_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):

A GIF that shows the customize sidebar with a select list of categories. The value of a select item is changed to something invalid via the dev tools and selected after that. Then an error message is displayed.

Leave a Reply

Your email address will not be published. Required fields are marked *