WordPress Quicky: Add User Profile Fields
If you want add fields to the wordpress user profile then two hooks are important for you.
The ‘show_user_profile’ counts if you open your profile and the ‘edit_user_profile’ if you open another users profile in admin.
function my_profile($user) { $fields = array('my_field1', 'my_field2'); // load already saved data from database foreach($fields as $key) { $$key = get_user_meta($user->ID, $key, true); } include dirname(__FILE__).'/profile.php'; } add_action('show_user_profile', 'my_profile'); add_action('edit_user_profile', 'my_profile'); |
In the profile.php is the html for our new fields. I change the positions of the fields with jQuery.
<div class="wrap">
<script type="text/javascript">
jQuery(function(){
jQuery('#my_field1').appendTo('.form-table:eq(1)');
jQuery('#my_field2').appendTo('.form-table:eq(2)');
});
</script>
<form action="?page=my_profile" method="post">
<table class="form-table">
<tr id="my_field1">
<th><label for="my_field1">Position</label></th>
<td><input type="text" name="my_field1" id="my_field1" value="<?=$my_field1?>" class="regular-text" /></td>
</tr>
<tr id="my_field2">
<th><label for="my_field2">Company*</label></th>
<td><input type="text" name="my_field2" id="my_field2" value="<?=$my_field2?>" class="regular-text" /></td>
</tr>
</table>
</form>
</div> |
i guess you want to save the new user fields to your wordpress database, so you have to add user meta.
function my_save_user($userId) { $fields = array('my_field1','my_field2'); if ($_POST) { foreach($fields as $key) { if (isset($_POST[$key])) { update_usermeta($userId, $key, $_POST[$key]); } } } } add_action('personal_options_update', 'my_save_user'); add_action('edit_user_profile_update', 'my_save_user'); |