1
votes

I'm using the following code to determine if a checkbox has been ticked and then display some text if it has/hasn't as a test.

When its checked, it works fine and the text displays.

When its unchecked I get the message below on the input box line with a comment in my code below.

Illegal string offset 'chec_checkbox_field_0'

<?php

    function webdev_init() {
    ?>
        <h1>Title</h1>
        <h2>WedDev Overlay Plugin Options</h2>
        <form action='options.php' method='post'>
        <h2>Checking</h2>

        <?php
        settings_fields( 'my_option' );
        do_settings_sections( 'checking' );
        submit_button();
        ?>

        </form>
    <?php
    }

    function chec_settings_init() {

        register_setting( 'my_option', 'chec_settings' );

        add_settings_section(
            'chec_checking_section',
            __( 'Your section description', 'wp' ),
            'chec_settings_section_callback',
            'checking'
        );

        add_settings_field(
            'chec_checkbox_field_0',
            __( 'Settings field description', 'wp' ),
            'chec_checkbox_field_0_render',
            'checking',
            'chec_checking_section'
        );
    }

    function chec_settings_section_callback() {

        echo __( 'This section description', 'wp' );

    }

    function chec_checkbox_field_0_render() {

        $options = get_option( 'chec_settings' );
    ?>

    //Error message on line bellow
    <input type='checkbox' name='chec_settings[chec_checkbox_field_0]' value='1' <?php if ( 1 == $options['chec_checkbox_field_0'] ) echo 'checked="checked"'; ?> />

    <?php
    }

 $options = get_option( 'chec_settings' );
if ( is_array( $options ) && $options['chec_checkbox_field_0'] == '1' ) {
    echo 'Checked';
} else {
    echo 'Unchecked';
}
1

1 Answers

0
votes

This means that the given index is not present in the array $options.

It seems that you are fetching the value of $options from HTTP request. As your input is a checkbox it is not present in the request when unchecked.

Because, in case of html form a checkbox is simply absent from the request after submission if it is unchecked.

It means checkbox has only two states either set or not set. So, you should check for isset() to identify if the checkbox is checked or not.

if ( isset( $options['chec_checkbox_field_0'] ) && $options['chec_checkbox_field_0'] == '1' ) {
    echo 'Checked';
} else {
    echo 'Unchecked';
}