Using WordPress ‘customize_sanitize_{$this->id}’ PHP filter

The customize_sanitize_{$this->id} WordPress PHP filter allows you to sanitize and validate the value of a specific Customize setting in an un-slashed form.

Usage

add_filter('customize_sanitize_my_setting_id', 'my_custom_function', 10, 2);

function my_custom_function($value, $setting) {
  // your custom code here
  return $value;
}

Parameters

  • $value (mixed): The value of the setting that needs to be sanitized and validated.
  • $setting (WP_Customize_Setting): The instance of the WP_Customize_Setting object.

More information

See WordPress Developer Resources: customize_sanitize_{$this->id}

Examples

Sanitize a text input

Sanitize a text input by removing HTML tags and escaping quotes.

add_filter('customize_sanitize_text_input', 'sanitize_text_input_function', 10, 2);

function sanitize_text_input_function($value, $setting) {
  // Strip HTML tags and escape quotes
  $value = wp_kses_post($value);
  return $value;
}

Validate an email address

Check if the value entered is a valid email address.

add_filter('customize_sanitize_email_input', 'sanitize_email_input_function', 10, 2);

function sanitize_email_input_function($value, $setting) {
  // Check if the value is a valid email
  if (is_email($value)) {
    return $value;
  }
  return '';
}

Sanitize a color input

Sanitize a color input by checking if it’s a valid hex color.

add_filter('customize_sanitize_color_input', 'sanitize_color_input_function', 10, 2);

function sanitize_color_input_function($value, $setting) {
  // Check if the value is a valid hex color
  if (preg_match('/^#[a-fA-F0-9]{6}$/', $value)) {
    return $value;
  }
  return '';
}

Limit the maximum number for a numeric input

Limit the maximum number that can be entered in a numeric input field.

add_filter('customize_sanitize_numeric_input', 'sanitize_numeric_input_function', 10, 2);

function sanitize_numeric_input_function($value, $setting) {
  // Set a maximum limit for the value
  $max_value = 100;
  if ($value > $max_value) {
    return $max_value;
  }
  return $value;
}

Sanitize a URL input

Sanitize a URL input by escaping the URL.

add_filter('customize_sanitize_url_input', 'sanitize_url_input_function', 10, 2);

function sanitize_url_input_function($value, $setting) {
  // Escape the URL
  $value = esc_url($value);
  return $value;
}