1

I am trying to create an options page with a checkbox field. The checkbox is working fine but when I uncheck it and save settings, an error string shows on

Notice: Uninitialized string offset: 0 in C:\xampp\htdocs\project\wp-content\plugins\test\admin\options.php on line 55

Here is the main settings code:

register_setting('twb_settings', 'twb_option', '' );

add_settings_section('twb_section', 'General Settings', '', __FILE__);

add_settings_field(  'hide_avatar',  'Hide Avatar',  'hide_vatar_fn',  __FILE__,  'twb_section');

function hide_vatar_fn()
{
    $options = get_option( 'twb_option' );      
    echo'<input type="checkbox" id="hide_avatar" name="twb_option[hide_avatar]" value="1" ' . checked(1, $options['hide_avatar'], false) . '/>';
}

If I add a sanitization call back in register_settings, then the error get replace with Undefined Variable error.

If I deactivate WP_Debug mode, all errors are gone.

2
  • and what is there on line 55? Nov 5, 2015 at 10:11
  • echo'<input type="checkbox" id="hide_avatar" name="twb_option[hide_avatar]" value="1" ' . checked(1, $options['hide_avatar'], false) . '/>';
    – bakar
    Nov 5, 2015 at 10:24

1 Answer 1

1

Most likely your $options is a string and not an array.

It is always better to validate that the $options are in the format you are expecting especially in development time when you are likely to switch formats and too lazy to clean the DB when doing that.

something like

if (!isset($options['hide_avatar'])) 
  $options['hide_avatar'] = 0;

Might have still resulted in a strange error, but it would have been little more easier to understand exactly where and maybe why.

3
  • where I am supposed to add this code? before echo'<input type="checkbox" .... ?
    – bakar
    Nov 5, 2015 at 12:17
  • you are not "supposed" to add that code anywhere, it is just a possible example to what you should do. The exact code and how/where to use it depends on how you prefer to write your code. Nov 5, 2015 at 12:26
  • My code was ended up like following and it fixed the issue. $options = get_option( 'twb_option' ); if (!isset($options['hide_avatar'])) $options['hide_avatar'] = 0; echo'<input type="checkbox" id="hide_avatar" name="twb_option[hide_avatar]" value="1" ' . checked(1, $options['hide_avatar'], false) . '/>'; and the problem was resolved.
    – bakar
    Nov 5, 2015 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.