Search code examples
phpwordpresscheckboxcheckedmeta-boxes

WordPress checked function with in_array


Wordpress plugin.
I need to checked="checked" for checkboxes. I store them in an array.

The problem I'm having is that if the checkboxes are stored they don't "check" the checkbox.

 public function display() {

    $html = '';
    // Add an nonce field so we can check for it later.
    wp_nonce_field( basename( __FILE__ ), 'nonce_check_value' );
    $html .= '<label for="CMBUserBoxName">Name metabox: </label>';
    $html .= '<input type="text" name="CMBUserBoxName" value="' . get_post_meta( get_the_ID(), 'CMBUserBoxName', true ). '">';
    $data = get_post_meta(get_the_ID(), 'CMBUserRequestedOption');
        echo '<pre>';
        print_r($data);
        echo '</pre>';

    $html .= 'Radio: ';
    $html .= '<input type="checkbox" name="CMBUserRequestedOption[Radio]" value="1" '.checked( in_array( 1, $data ), 1, false ).' />';



    $html .= '</br>';

    $html .= 'Checkbox: ';
    $html .= '<input type="checkbox" name="CMBUserRequestedOption[Checkbox]" value="1" '.checked( in_array( 1, $data ), 1, false ).' />';


    echo $html;
}

print_r($data) =

Array
(
    [0] => a:2:{s:5:"Radio";s:1:"1";s:8:"Checkbox";s:1:"1";}
)

The save function:

if(isset($_POST['CMBUserRequestedOption'])  ){
      $data=serialize($_POST['CMBUserRequestedOption']);

      update_post_meta($post_id, 'CMBUserRequestedOption', $data);

I think the checked() is missing something.
checked( in_array( 1, $data ), 1, false )


Solution

  • Your $data contains a serialized string (at index 0). If you want to check the data it contains, you have to unserialize it.

    $data = Array(
        'a:2:{s:5:"Radio";s:1:"1";s:8:"Checkbox";s:1:"1";}'
    );
    $data[0] = unserialize($data[0]);
    

    Then you could use checked($data[0]['Radio'], 1, false):

    $html .= '<input type="checkbox" name="CMBUserRequestedOption[Radio]" value="1" '.checked($data[0]['Radio'], 1, false).' />';
    $html .= '<input type="checkbox" name="CMBUserRequestedOption[Checkbox]" value="1" '.checked($data[0]['Checkbox'], 1, false).' />';
    

    Or as pointed out by @Nawin, you can get the data in a value, instead of array:

    $data  = get_post_meta(get_the_ID(), 'CMBUserRequestedOption', true);
    $data = unserialize($data);
    // echo checked($data['Radio'], 1, false);
    // echo checked($data['Checkbox'], 1, false);
    
    $html .= '<input type="checkbox" name="CMBUserRequestedOption[Radio]" value="1" '.checked($data['Radio'], 1, false).' />';
    $html .= '<input type="checkbox" name="CMBUserRequestedOption[Checkbox]" value="1" '.checked($data['Checkbox'], 1, false).' />';
    

    See also maybe_unserialize().