0

all

Now i create a widget plugin, here i have problem the checkbox problem, dont have save the value, then i search form Net, and found the answer, but now i dont have understand the means of (bool).

        <label for="<?php echo $this->get_field_id( 'post_date' ); ?>">
    <input class="checkbox" type="checkbox" name="<?php echo $this->get_field_name( 'post_date' ); ?>" id="<?php echo $this->get_field_id( 'post_date' ); ?>"  <?php checked( (bool) $instance['post_date'], true ); ?> />
    <?php _e( 'Show post date' ); ?>
  </label>
1

I also got this problem before. I try to use the (bool) but the problem still occured.

(bool) $instance['post_date']

will always return true unless $instance['post_date'] is an empty array, NULL or empty string

you can check this from http://php.net/manual/en/language.types.boolean.php

<?php
    var_dump((bool) "");        // bool(false)
    var_dump((bool) 1);         // bool(true)
    var_dump((bool) -2);        // bool(true)
    var_dump((bool) "foo");     // bool(true)
    var_dump((bool) 2.3e5);     // bool(true)
    var_dump((bool) array(12)); // bool(true)
    var_dump((bool) array());   // bool(false)
    var_dump((bool) "false");   // bool(true)
?>

so to handle this problem, I print the $instance['post_date'] and get the value 'on'. So now my code currently look something like this and working perfectly.

<?php checked( $instance['post_date'], 'on' ); ?>
1
  • Upvote for 'on' doing the trick! – Dave Romsey Sep 22 '11 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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