how to save checkbox data for custom setting?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x