C.Bavota wrote a nice tutorial on adding user profile fields to the WordPress database by modifying the functions.php file in your WordPress theme. I followed his article with success; however, I ran into difficulty when adding checkboxes. Here is my addition to his good code.
To use checkboxes, you need to do two things:
- First, you need to set a “value” for the checkbox input element (I use value=”yes”).
- Second, you need to appropriately set the “checked” attribute of the <input> element.
See the code below.
<input type="checkbox" name="my_field" id=" my_field " value="yes" <?php if (esc_attr( get_the_author_meta( "my_field", $user->ID )) == "yes") echo "checked"; ?> /><label for="my_field "><?php _e("My Field"); ?></label><br />
The code above queries the current value of the field from the database; if it should be checked, then the PHP will write the “checked” attribute into the <input> element. The resulting HTML looks like this:
<input type="checkbox" name="my_field" id=" my_field" value="yes" checked class="regular-text" />
recommended using checked=”checked”; I tried that, and it seemed to always leave the checkbox checked. If you figure it out, please let me know
, since I believe that is the “correct” way to do it, per W3C Recommendation
The code to update checkbox fields is the same for textbox fields (C.Bavota’s tutorial
update_user_meta( $user_id, 'my_field', $_POST['my_field'] );
Update 30 Mar 2012
: This code is for adding checkbox fields to the user profile page. You may want to add some of these fields to the registration form. To do that, I use Theme My Login
, following Jeff Farthing’s example code
. In sort, it involves editing two PHP files: one in your theme directory and one in the plugins directory.