Checked checkbox?

I’m working on adding a checkbox to my user registration page to opt-in to my e-mail list, and I’m not sure the proper way to have the checkbox ticked off by default. This is what I’ve got so far:

// Checkbox to join list
add_action( 'register_form', 'email_opt_in' );

function email_opt_in() { ?>
    <p>
    <label style="font-size:13px;">
    <input type="checkbox" name="email_opt_in" id="email_opt_in" class="input" value="1" <?php checked( $_POST['email_opt_in'], 1 ); ?> tabindex="99" style="width:12px;padding:0;margin: 0 3px 0 0;font-size: 13px;" /> 
    Join our famous e-mail list
    </label>
    </p>
    <br/><?php
}

I’m using checked which works great, but I want the checkbox to be checked by default. Is adding checked="checked" to input the right thing to do, or is there a better way to do it?

Read More

Thanks in advance!

Related posts

Leave a Reply

3 comments

  1. I would add a hidden input field with the same name before the checkbox:

    <input type="hidden" name="email_opt_in" value="0" />

    Because the forms are processed sequentially you would get “0” if the form was submitted, but the checkbox wasn’t checked (instead of not getting anything).

    Then assume the checkbox is checked if the form wasn’t submitted or if it was submitted and the checkbox was checked:

    $checked = !isset($_POST['email_opt_in'])
                 || (isset($_POST['email_opt_in']) && $_POST['email_opt_in']);
    

    Later:

    ... <?php checked($checked); ?>

    The entire idea is to store the unchecked state of the checkbox in case of an input error, so the user doesn’t have to check it again if he didn’t want to on the first submission.

    Sorry for this long and boring answer for this simple question 🙂

  2. You need to pass the actual current value of the option to checked(), rather than the $_POST value.

    How are you registering your options, and how are you referencing them in your form?