jeudi 22 mars 2018

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 )




Aucun commentaire:

Enregistrer un commentaire