How to modify users contact info using a simple function

Difficulty Difficulty Difficulty Posted Posted by Fulippo in Tutorials     Comments 1 comment
Mar
10

One of the greatest feature of WordPress, on the side of code, is the way filters and hooks make you life really easy when you try to modify default behaviours.

In this tutorial we assume you are already comfortable with hooks and filters. If not so take a look at the codex to learn more about the hooks/fillters logic.

WordPress users contact details usually looks as shown in picture:

As default, we only have few fields: E-mail, website, AIM, Yahoo IM and Jabber / Google Talk. So how can we add more fields (or remove some unused ones) to fit our needs?

The solution is the user_contactmethods hook. By assigning a custom callback function to this hook (in the functions.php file of our theme for example) we will be able to manipulate all above fields (except for e-mail field)

So, for example, if you want to add more fields just put these lines of code inside functions.php:

1
2
3
4
5
6
7
8
9
10
function my_contactmethods( $contactmethods ) {
 
	$contactmethods['my_other_website'] = 'My Other Website';
	$contactmethods['my_phone_number'] = 'My Phone Number';
	$contactmethods['my_skype'] = 'My Skype Contact';
	$contactmethods['my_credit_card'] = 'My Credit Card Number ;)';
 
	return $contactmethods;
}
add_filter('user_contactmethods','my_contactmethods',10,1);

All available fields are enclosed inside an array, called $contactmethods, so, by using a callback function, you can easily add or remove any field you want.

In the example above we add 4 fields which will be available, through user_metadata, to every user.

If you just want to remove some unused field, do as follow:

1
2
3
4
5
6
7
8
9
function my_contactmethods( $contactmethods ) {
 
	unset($contactmethods['aim']);
	unset($contactmethods['yim']);
	unset($contactmethods['jabber']);
 
	return $contactmethods;
}
add_filter('user_contactmethods','my_contactmethods',10,1);

Using unset will remove the contact methods from the form.

Code is poetry ;)

1 Comment to “How to modify users contact info using a simple function”

  • Does this add a record to the database as well? If not, can you share how to do so?

    Thanks!

    Kindly,

    Michael

Post comment