-
-
Save ajskelton/2ed4017fa0842bae49b99888daa998b3 to your computer and use it in GitHub Desktop.
Invalid value error after publishing in Customizer due invalid sanitize_callback function name. Suggestion, rename function themeslug_sanitize_select to themeslug_customizer_sanitize_radio.
Is it possible to give an example on how to use this code correctly? Thanks.
Is it possible to give an example on how to use this code correctly? Thanks.
The only error in the code was the wrong name for the function that does the sanitizing. The first comment here mentioned it was called _sanitize_radio
and I only corrected it in the first instance.
To see a full example of using the code you can see my blog post on using all the customizer settings, https://anthonyskelton.com/2016/rediscover-wordpress-customizer/. However it is four years old so I can't speak to how current all of the information is.
I did a quick test with the above code ( with the correct name on the sanitize function ) and it worked no problem for me on a fresh twenty_twenty child theme. Here is the code I used for that test that includes adding a panel and section and hooking it all to the customize_register
action.
function themeslug_customize_register( $wp_customize ) {
$wp_customize->add_panel(
'panel_id',
array(
'priority' => 160,
'title' => __( 'Child Theme Settings'),
'description' => __( 'Controls for the child theme of twenty twenty'),
'capability' => 'edit_theme_options'
)
);
$wp_customize->add_section(
'section_id',
array(
'priority' => 10,
'title' => __( 'Test Section' ),
'description' => __( 'Section Description' ),
'panel' => 'panel_id',
)
);
$wp_customize->add_setting( 'themeslug_radio_setting_id', array(
'capability' => 'edit_theme_options',
'default' => 'blue',
'sanitize_callback' => 'themeslug_customizer_sanitize_radio',
) );
$wp_customize->add_control( 'themeslug_radio_setting_id', array(
'type' => 'radio',
'section' => 'section_id',
'label' => __( 'Custom Radio Selection' ),
'description' => __( 'This is a custom radio input.' ),
'choices' => array(
'red' => __( 'Red' ),
'blue' => __( 'Blue' ),
'green' => __( 'Green' ),
),
) );
}
add_action( 'customize_register', 'themeslug_customize_register' );
function themeslug_customizer_sanitize_radio( $input, $setting ) {
// Ensure input is a slug
$input = sanitize_key( $input );
// Get a 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 );
}
Thanks, this is a very nice working example. And with custom values!
You might want to rename the function to themeslug_sanitize_radio(). rn it's still called select