How to Use Checkbox in Custom Option Page Using The Setting API

Can you please let me know how I can add a checkbox to Setting API in creating Custom Options Page? I am using the following code to add a txt box which is working perfectly but I am totally confused how to add chechbox to the setting API and options. I just tried ti update the input type to checkbox but I am not sure what to put in Value besides when I save the form the check box still appears unchecked!

 add_settings_field('the_option_label',
                    'Display Paragraph:',
                     array($this,'the_option_label_setting'),
                     __FILE__,
                     'hte_main_section');

 public function the_option_label_setting()
    {
       echo "<input name='My_Theme_Options[the_option_label]' type='text' value='{$this->options['the_option_label']}'/>";
    }

Thanks

Related posts

1 comment

  1. Have a look at: The Complete Guide To The WordPress Settings API (Part 8: Validation, Sanitisation, and Input II):

    add_settings_field(  
        'Checkbox Element',  
        'Checkbox Element',  
        'sandbox_checkbox_element_callback',  
        'sandbox_theme_input_examples',  
        'input_examples_section'  
    );
    
    function sandbox_checkbox_element_callback() {
    
        $options = get_option( 'sandbox_theme_input_examples' );
    
        $html = '<input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" value="1"' . checked( 1, $options['checkbox_example'], false ) . '/>';
        $html .= '<label for="checkbox_example">This is an example of a checkbox</label>';
    
        echo $html;
    
    }
    

    EDIT: Check box fields do not use the value attribute to determine if the box is checked. They use a checked attribute. The $html line above has been edited using the code from later in the article referenced above. Read the articles for details.

Comments are closed.