Automatically Link Twitter Usernames in Posts And Comments

How to Automatically Link Twitter Usernames in Posts And Comments

in Social Media
Google+ LinkedIn

Have you ever wonder how some websites allow you to enter a user’s Twitter handle (username preceded by a @ symbol) and automatically turn it into a link to that users Twitter profile page? If you frequently mention user’s twitter handles in your blog post content, then I think you will going to love this code snippet. It will save lots of your time by automatically link twitter usernames in your WordPress posts as well post comments.

Although there are some third-party JavaScript solutions available for the same but I don’t know why would you want to choose those over WordPress. Instead of relying on these scripts, you can achieve this fairly easily with a little PHP and WordPress filters.

All you have to do is to paste this code snippet in your theme’s functions.php file and WordPress will automatically link twitter usernames in your posts as well as in comments to their twitter profiles. For example this snippet will transform @WPCodeSnippet into @WPCodeSnippet.

// automatically link twitter usernames in posts and comments
function wcs_twitter_usernames( $content ) {
	$twitter_username = preg_replace( '/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/', '$1<a href="http://twitter.com/$2" target="_blank" rel="nofollow">@$2</a>', $content );
	return $twitter_username;
}
add_filter( 'the_content', 'wcs_twitter_usernames' );
add_filter( 'comment_text', 'wcs_twitter_usernames' );

It’s important to note that Twitter handles should be written in this format @username.

image source

Share the love

If you like this snippet, share it with others!

2 Replies on "Automatically Link Twitter Usernames in Posts And Comments"

  1. Svend Rugaard

    Does this actually work ? Because i just get “blank” site when i at it to functions.php in my child theme

    1. Yes it does. It simply use preg_replace PHP function to automatically link twitter usernames in posts and comments.

      Try it out and let us know if you find any issue. :)

Leave a Reply

Your email address will not be published. Required fields are marked *