The WordPress Profile page allows you to define an email address and website, which you can then display on your site. Wouldn’t it be nice if you could define additional contact methods like GitHub, LinkedIn, and Twitter accounts? Let’s learn how to add more contact fields and display them on your site!
Add New Contact Options
To add new contact options to the WordPress Profile page, we’ll utilize the user_contactmethods filter hook. Navigate to Appearance > Theme Editor and open the template file in your theme called functions.php. Add the following code to it.
add_filter( 'user_contactmethods', 'my_custom_user_contact_methods' );
The second parameter in the add_filter function is the name of the function you want to call. Let’s create that function now. It receives the current contact options as an argument. Let’s call them $options. Add the new options with the text that should appear as the field label and then return the options.
// Add user contact methods.
function my_custom_user_contact_methods( $options ) {
$options['github'] = __( 'Github Username' );
$options['linkedin'] = __( 'LinkedIn Username' );
$options['twitter'] = __( 'Twitter Username' );
return $options;
}
Keep in mind that if you switch to a different theme, you would lose this functionality because it was added to your current theme’s functions.php file. If you want this functionality to persist, make it a WordPress plugin instead.
Display New Contact Options
To display a WordPress user’s (author) information, we first have to know which user we’re talking about. We need the user’s unique id.
To get the user’s id outside of the WordPress loop, use the following:
global $post;
$authorId = $post->post_author;
To get the user’s id inside the WordPress loop, use the following:
$authorId = get_the_author_meta( 'ID' );
Now let’s get the values of the new contact fields we created in the prior section. We can utilize the get_the_author_meta function again. The first argument defines the field you’d like retrieve about the user. The second argument defines the user’s unique id.
$github = get_the_author_meta( 'github', $authorId );
$linkedin = get_the_author_meta( 'linkedin', $authorId );
$twitter = get_the_author_meta( 'twitter', $authorId );
Display the values wherever you’d like.
<a target="_blank" href="https://github.com/<?php echo $github; ?>">GitHub</a>
<a target="_blank" href="https://linkedin.com/in/<?php echo $linkedin; ?>">LinkedIn</a>
<a target="_blank" href="https://twitter.com/<?php echo $twitter; ?>">Twitter</a>
Top comments (0)