I have this buggy sanitization function for "select" control:

function sanitize_select( $input, $setting )
    $input = sanitize_key( $input );
    $control = $setting->manager->get_control( $setting->id );
    $choices = $control->choices;
    return ( array_key_exists( $input, $choices ) ? $input : $setting->default );

Value of $control variable is always null because the method get_control() expects "control ID" and not "setting ID"

I can't figure out a way to get the ID of the control, any Ideas?


I think this is probably not right approach for the way the Customiser is organised.

Controls and Settings are pretty much separate entities. Controls can save settings, but settings aren't tied to a specific control. As far as I'm aware there's nothing stopping you having multiple controls for a single setting, for example.

My suggestion would be to abstract the choices into a separate function or variable, and then just reference it in the appropriate places. For example, have this function that defines the valid choices:

function wpse_316500_choices() {
    return [
        'one'   => 'One',
        'two'   => 'Two',
        'three' => 'Three',

And then use that function when registering the control:

$wp_customize->add_control( 'wpse_316500_setting',
        'type'    => 'select',
        'choices' => wpse_316500_get_choices(),

And also in the sanitisation function:

function wpse_316500_sanitize( $input, $setting ) {
    $input = sanitize_key( $input );
    $choices = wpse_316500_get_choices();

    return ( array_key_exists( $input, $choices ) ? $input : $setting->default );
  • Man that's brilliant, do you think doing separate sanitization function for each "select control setting" is better than multiple controls for single setting – Rozo Oct 12 '18 at 1:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.