User Contact Fields in WordPress

WordPress comes with a “default” set of user contact fields, which has always looked random to me: AIM, Yahoo IM and Jabber / Google Talk, instead of what I’d want to have there: Twitter, Facebook and Google+. A while back I got frustrated enough to have a look at how this was actually dealt with in the backend of WordPress, and fix it, so in WordPress 2.9 an API was added as a result of ticket #10240.

This change allowed for developers to add user contact fields in a very simple way. The example code below adds Twitter and removes Yahoo IM, and yes, this is all the code that’s needed to do it:

function add_twitter_contactmethod( $contactmethods ) {
  // Add Twitter
  if ( !isset( $contactmethods['twitter'] ) )
    $contactmethods['twitter'] = 'Twitter';

  // Remove Yahoo IM
  if ( isset( $contactmethods['yim'] ) )
    unset( $contactmethods['yim'] );

  return $contactmethods;
}
add_filter( 'user_contactmethods', 'add_twitter_contactmethod', 10, 1 );

Easy does it, right? Retrieving the user contact field isn’t much harder either, for example, if you’re on a singular page, use the following code:

if ( is_singular() ) {
  global $post;
  $twitter = get_the_author_meta( 'twitter', $post->post_author );
}

And there you have it! My WordPress SEO plugin uses this exact method to add a Google+ profile field for users to be used in conjunction with the author highlighting features of Google. If you’d want to echo the Google+ user contact field that plugin creates, do the following:

if ( is_singular() ) {
  global $post;
  the_author_meta( 'googleplus', $post->post_author );
}

As you can see this uses the_author_meta instead of get_the_author_meta. The $post global and the $post->post_author reference would strictly speaking not even be needed as they’re called from the global otherwise within the function, but this might prevent issues with retrieving the wrong user contact fields.

That’s it! Now you can add and remove user contact fields as you wish. You can do this in your theme’s functions.php or in a plugin, be sure to add the isset code around it to prevent notices though!

User Contact Fields in WordPress is a post by on Yoast – Tweaking Websites.A good WordPress blog needs good hosting, you don’t want your blog to be slow, or, even worse, down, do you? Check out my thoughts on WordPress hosting!