So I've created some options for the theme customizer with sanitize callbacks. I want to be able to change those options with $_GET
requests, but letting only valid values to pass, as they are specified in the sanitize_callback
function.
Here is my code:
function _wp007432_customize_register( $wp_customize ) {
$wp_customize->add_section( 'section_header' , array(
'title' => esc_html__('Header', 'wp007432'),
'panel' => '_wp007432_options_panel',
));
$wp_customize->add_setting( 'header_layout', array(
'default' => '1',
'sanitize_callback' => '_wp007432_sanitize_header_layout',
));
$wp_customize->add_control( 'header_layout', array(
'label' => esc_html__( 'Header Layout', 'wp007432' ),
'section' => 'section_header',
'type' => 'radio',
'choices' => array(
'1' => esc_html__( 'Header style 1.', 'wp007432' ),
'2' => esc_html__( 'Header style 2.', 'wp007432' ),
'3' => esc_html__( 'Header style 3.', 'wp007432' ),
),
));
}
add_action( 'customize_register', '_wp007432_customize_register' );
Sanitize the option so that only valid values will pass:
function _wp007432_sanitize_header_layout( $input ) {
$valid = array(
'1' => esc_html__( 'Header style 1.', 'wp007432' ),
'2' => esc_html__( 'Header style 2.', 'wp007432' ),
'3' => esc_html__( 'Header style 3.', 'wp007432' ),
);
if ( array_key_exists( $input, $valid ) ) {
return $input;
}
return '';
}
In my theme I use this option like:
get_theme_mod('header_layout', '1');
Now let's say I want to change the option using $_GET
:
if ( isset($_GET['header_layout']) ) {
add_filter( 'theme_mod_header_layout', function(){
return $_GET['header_layout'];
});
}
Now if I understood correctly, if I pass a non-valid value, like 10
, the theme mod must fall back to default. But it's not happening. Am I doing it wrong?
Sure, I can check the $_GET
value in the filter, but it's extra code, and what's the point if sanitization then?