Automatically Link Twitter Usernames in Posts And Comments

[ad_1]

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



[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads