This is an unexpected behaviour in the customizer preview, when using 'default' => true
with a checkbox
.
Use case
I add a checkbox control to the customizer (any page it doesnt matter):
$wp_customize->add_setting( 'my-checkbox', array(
'type' => 'option',
'capability' => 'manage_options',
'transport' => 'refresh',
'default' => true ///HERE I SET THE DEFAULT "TRUE"
) );
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'my-checkbox',
array(
'label' => __( 'A checkbox checked by default' ),
'section' => 'any-page',
'type' => 'checkbox'
) ) );
i use it anywhere like this:
get_option( 'my-checkbox', true ); //since its TRUE by default, here as well its TRUE
so far its okay, if i open the customizer i see this, using a var_dump()
, in this case using it in the home page:
in the homepage
without opening the customizer i will get TRUE
so thats okay.
But now if i uncheck it in the customizer, i get this:
which is the default from the get_option( 'my-checkbox', true )
this issue its in the customizer-preview
the homepage
will have the correct value if visited directly.
if i want the value to be FALSE
(unchecked), i need to save 2 times, the first time to have the option saved so there is no default
value, and the second time to actually save the value of FALSE
(unchecked).
Is this a bug in wordpress
? debugging
it more, i found i am getting the 'default' => true
, in the get_option( 'my-checkbox', true );
which is something i set when creating the control, this when using the customizer.
Here i am changing it to another default type, so its more clear:
get_option( 'my-checkbox', 'default' );
in the homepage
, i get the correct value:
in the customizer
i get TRUE
:
which is wrong since in the homepage
opening it directly i get default
what can be done? i dont want to pull a global variable to just check if i am in the customizer.
First when you create code and set default value then that value not set to the database that is why we need to use get_theme_mod function. This function needs to arguments like first the name and second is the default what you want to show. Then if the value saved to the database then the function returns the database value otherwise it will show the default value which you have added in second arguments. I hope this will help you...