Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

Thanks in advance!

share|improve this question
    
Adding checked="checked" is not the right thing to do to default check a checkbox. It's THE HTML CORRECT thing to do, the only thing to do. –  EarnestoDev Oct 26 '11 at 21:52
add comment

3 Answers

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?

share|improve this answer
    
I don't think there is a current value, this doesn't look like something that you want recorded –  onetrickpony Oct 27 '11 at 0:16
add comment

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 :)

share|improve this answer
add comment

As you want to be checked the checkbox by default, there is no way rather than checked="checked" in HTML.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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