Friday, May 31, 2013

My Wordpress learning series: Adding and saving values from a drop down list using theme my login plugin

This article marks the beginning of my experience of diving into the massive world of “wordpress” that could help a lot of newbie and struggling wordpress developers.

After struggling for days together to achieve the functionality to add extra fields to a user profile form using “theme my login”, and having looked up 1000’s of articles from Google, I could finaaly gather the following means to be able to add and save values from a dropdown list into the wordpress database.

You will find a number of articles on “How to add extra “text” type fields but none mentions “How to add fields from a drop down list and save them”(In case you do find them, please drop in a link in “comments” below).
So, here I am, unleashing my step-by-step experience of adding and saving values from a dropdown list using “theme my login” plugin (I have used Steven Ray’s example of auto populating country list in the dropdown)

In this example, we will use the following 2 templates (“register-form.php” and “theme-my-login-custom.php”)
Adding the new field:

  • ·   First, create a copy of /wp-content/plugins/theme-my-login/templates/register-form.php into your current theme’s directory. Edit this template and add the new field as described below. As mentioned earlier, I will be using excerpts from this example to auto-fill my list with “countries” first and then save it into the database. 
  • Insert the following code to the copy of register-form.php you created earlier anywhere between the <form> and</form> tags.
Saving the new field:
  • Create theme-my-login-custom.php under /wp-content/plugins/as described here.

“Theme my login” is an excellent plugin to create user profile forms. The author has written a well detailed tutorial on Adding Extra Registration Fields. Taking cue from the same and Steven Ray’s example, I could devise my own and compose this post.

<?php $xmlcountries = '';?>
<select name="custom_country" id="custom_country">
<?php  $countries = simplexml_load_file($xmlcountries);?>
<option value="">Your country</option>
<?php foreach ($countries->country as $country) {
    echo '<option value="'.$country->geonameId.'|'.$country->countryName.'">'.$country->countryName.'</option>';


·         Add the following lines to it:
function tml_user_register( $user_id ) {
if ( !empty( $_POST['custom_country'] ) )
                                update_user_meta( $user_id, 'custom_country', $country );

add_action( 'user_register', 'tml_user_register' );
And now test out the registration form…

You can see the populated list of countries below:

And after you click “Register”, don’t forget to check out the saved field in the database.

Yippee, there’s mine right up there!!!

Post a Comment