Add Custom User Fields to your WordPress Installation

I wanted to make a quick post to show off a neat little trick in WordPress – adding custom user fields to a user’s profile. This could be used to add in space for a Twitter Handle, a Facebook link, a second portfolio site, or any combination of the above.

For the demo purposes, let’s assume that a store owner is using WooCommerce to run their online store, but has transitioned from another CMS. The other CMS identified users by an Account Number – that information has to be kept in the new system.

To achieve this, we’ll add an Account Number field into the User Profile by including the following code in your functions.php file:

Adding a Custom Field into a WordPress User Page

// Add User Account Number
function customer_acct_number($profile_fields) {
    // Add new fields
    $profile_fields['acctno'] = 'Account Number';
    return $profile_fields;
}
add_filter('user_contactmethods', 'customer_acct_number');

Then, on that user’s public facing profile, you may want to display the field. To display, use the $customer_account_no variable and also include the following in your functions.php:

// Retrieve a custom field value
    $customer_account_no = get_the_author_meta('acctno');

Additional Tricks

The code above will automatically insert this in the "Contact Information" area of a user profile, but can be changed to any hook using the WordPress Filter reference Codex Page. This feature can also be repeated to add multiple fields at once – the following code will add fields for Facebook URLs, Google+ URLs, and Twitter Handles:

// Add User Account Number
function customer_acct_number($profile_fields) {
    // Add new fields
    $profile_fields['facebook_url'] = 'Facebook URL';
    $profile_fields['gplus_url'] = 'Google + URL';
    $profile_fields['twitter_url'] = 'Twitter URL';
    return $profile_fields;
}
add_filter('user_contactmethods', 'customer_acct_number');

Which in turn, could be given the following variables:

// Retrieve a custom field value
    $customer_facebook_url = get_the_author_meta('facebook_url');
    $customer_gplus_url = get_the_author_meta('gplus_url');
    $customer_twitter_url = get_the_author_meta('twitter_url');

I hope this helps!

Leave a Comment