Getting error to display radio button value in General Settings page

I’m constantly getting the errors bellow when printing the radio button values from General Settings screen:

Illegal string offset ‘service’ in F:wampwwwplugin-testerwp-contentthemestwentythirteenfunctions.php on line 565

Read More

Illegal string offset ‘service’ in F:wampwwwplugin-testerwp-contentthemestwentythirteenfunctions.php on line 568

Here is the code which I added to functions.php file:

add_filter('admin_init', 'myservice_register_function');
function myservice_register_function(){
    register_setting('general', 'my_service', 'esc_attr');
    add_settings_field('my_service', '<label for="service_need">'.__('Do You need My    Service' , 'my_service' ).'</label>' , 'service_function', 'general');
}

function service_function(){
    $options = get_option( 'my_service', '');
    //  $options = get_settings( 'my_service');

    if($options['service'] == 'YES') { //line number 565
        echo 'Yes, Service Need'; 
    }
    if($options['service'] == 'NO') { // line number 568
        echo 'No Need Service';
    }
    $html = '<input type="radio"  name="my_service[service]" value="YES"/>'; 
    $html .= '<label> NEED </label>'; 

    $html .= '<input type="radio"  name="my_service[service]" value="NO"/>'; 
    $html .= '<label > NO NEED </label>'; 

    echo $html;
}

What’s the mistake?

Related posts

1 comment

  1. Apart from the isset issue, pointed by Rarst, there’s an error in the sanitization function. esc_attr seems not to work with radio buttons, using esc_sql does the job.
    You’re also missing the checked state for the buttons:

    add_filter( 'admin_init', 'myservice_register_function' );
    
    function myservice_register_function()
    {
        register_setting( 'general', 'my_service', 'esc_sql' );
        add_settings_field(
            'my_service', 
            '<label for="service_need">'.__('Do You need My Service' , 'my_service' ).'</label>' , 
            'service_function', 
            'general'
        );
    }
    
    function service_function()
    {
        $options = get_option( 'my_service', '');
        $yes = $no = '';
        if( isset( $options['service'] ) )
        {
            if( $options['service'] == 'YES') 
            {
                echo 'Yes, Service Need<br />'; 
                $yes = ' checked="checked"';
            }
            if( $options['service'] == 'NO') 
            {
                echo 'No Need Service<br />';
                $no = ' checked="checked"';
            }
        }
        ?>
        <input type="radio"  name="my_service[service]" value="YES"<?php echo $yes; ?> />
        <label> NEED </label>
    
        <input type="radio"  name="my_service[service]" value="NO"<?php echo $no; ?> />
        <label> NO NEED </label> 
        <?php
    }
    

Comments are closed.