select sanitize_callback in WP customizer

wordpress

#1

Hi,

What should be the “sanitize_callback” for select? If I do not add “sanitize_callback” for select it will show this error message in Theme Check

REQUIRED: Found a Customizer setting that did not have a sanitization callback function. Every call to the add_setting() method needs to have a sanitization callback function passed.

or the reviewer will allow this?

I tried using this code

'sanitize_callback' => 'esc_url_raw',

but I think it is only for URL…

anyone can help me?

Thanks


#2

for select
if ( ! function_exists( ‘themename_sanitize_select’ ) ) :

/**
 * Sanitize select.
 *
 * @since 1.0.0
 *
 * @param mixed                $input The value to sanitize.
 * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
 * @return mixed Sanitized value.
 */
function themename_sanitize_select( $input, $setting ) {

	// Ensure input is a slug.
	$input = sanitize_key( $input );

	// Get list of choices from the control associated with the setting.
	$choices = $setting->manager->get_control( $setting->id )->choices;

	// If the input is a valid key, return it; otherwise, return the default.
	return ( array_key_exists( $input, $choices ) ? $input : $setting->default );

}

endif;


#3

thanks but I’m not sure on your code… I am only asking the ‘sanitize_callback’ => ‘’, for select…


#4

call the above function name in sanitize_callback’ => ‘’, for select.


#5

You would need to create a function and then set the callback to that function e.g.

'sanitize_callback' => 'theme_sanitize_numbers',

function theme_sanitize_numbers( $input ) {
 $valid = array(
  '1' => '1',
  '2' => '2',
  '3' => '3',
  '4' => '4',
  '5' => '5',
  '6' => '6',
  '7' => '7',
  '8' => '8',
  '9' => '9',
  '10' => '10',
 );
 if ( array_key_exists( $input, $valid ) ) {
  return $input;
 } else {
  return '';
 }
}

The options in the function need to match exactly what are in your select choices e.g.

$wp_customize->add_control(
  'theme_numbers',
  array(
   'type' => 'select',
   'label' => 'Speed (in seconds)',
   'section' => 'something',
   'choices' => array(
    '1' => '1',
    '2' => '2',
    '3' => '3',
    '4' => '4',
    '5' => '5',
    '6' => '6',
    '7' => '7',
    '8' => '8',
    '9' => '9',
    '10' => '10',
   ),
  )
 );

#6

Thanks gareth… this helps a lot…