I have been trying to add a checkbox into the theme customizer. I have a checkbox added using this code in my functions.php
function theme_customizer_register_checkbox($wp_customize) {
$wp_customize->add_section( 'savior_global_options', array(
'title' => 'Global Options',
) );
$wp_customize->add_setting( 'show_supporters', array(
'default' => true,
'type' => 'option',
'capability' => 'edit_theme_options' )
);
$wp_customize->add_control( 'display_supporters', array(
'settings' => 'show_supporters',
'label' => 'Show supporters section',
'section' => 'savior_global_options',
'type' => 'checkbox',
) );
}
add_action( 'customize_register', 'theme_customizer_register_checkbox' );
Once I got the checkbox working. I found that when I checked the box, it wouldn’t change state. It always stayed checked. I did some searching and found post on this site that was solved but didn’t leave an answer. The post led me to think that I needed to change the value in my $wp_customize->add_control()
function to a unique value. So I changed it to display_supporters
. This solved my issue but now I can’t get the value of the checkbox. When I dump this variable,
$supporters = get_theme_mod('display_supporters);
I get bool(false)
and it stays at that. no matter what I do to the checkbox. What am I missing?
I was able to solve this. Here is the code that got the checkbox working.
Then I checked for the value in the front end like so
I’m pretty sure your theme modification setting isn’t displaying as you’re saving it as an option. You’re setting it to save as an option in the
$wp_customize->add_setting
method with the'type' => 'option'
argument.As it’s an option you could retrieve it using
get_option( 'show_supporters' )
instead. Note that ‘show_supporters’ is the name of the setting you’ve created not display_supporters.However unless your theme already has a settings panel it’s probably best to store it in your theme’s modification settings. You can then use
get_theme_mod( 'show_supporters' )
to get your value. Otto on WordPress has written a good article about replacing option pages with the theme customizer.I could only reproduce the problem with the checkbox not unchecking if the id of the add_setting and add_control methods did not match. I’ve included the code that worked for me below.