how to save checkbox data for custom setting?

The question:

I am creating one custom setting panel, my codes are

function custom_text_field_html(){
 
    $text = get_option( 'homepage_text' );
 
    printf(
        '<input type="text" id="homepage_text" name="homepage_text" value="%s" />',
        esc_attr( $text )
    );
 
}

function custom_checkbox_field_html(){
 
    $checkbox = get_option( 'disabletitle_text' );
 
    printf(
        '<input type="checkbox" id="disabletitle_text" name="disabletitle_text" value="1" />',
        esc_attr( $checkbox )
    );
 
}

my checkbox data is not saving, how to save checkbox data like ‘text field’, so that I can call them in functions, if someone checked the field ‘enable that function’, if someone ‘not checked the field’, disable the function.

I referred this http://qnimate.com/add-checkbox-using-wordpress-settings-api/, but it’s showing error in my case

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Your checkbox data is saved as 1 or '' if someone checked or unchecked it.

you can also verify this using var_dump($checkbox) inside custom_checkbox_field_html function

This should work.

function custom_checkbox_field_html(){
 
    $checkbox = get_option( 'disabletitle_text' );
    $is_checked = (  $checkbox != '' && $checkbox == 1 ) ? 'checked': '';

    printf(
        '<input type="checkbox" id="disabletitle_text" name="disabletitle_text" value="1" %s/>',
        esc_attr( $is_checked )
    );
 
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment