Wordpress

How to Automatically Link Twitter Usernames in WordPress

Two years ago, Twitter launched Twitter Anywhere API which made it really easy for us to mention twitter usernames and have them be automatically linked to the right profile. It also allowed for beautiful hovercards with additional info. Sadly Twitter has decided to retire the Anywhere API on December 6th, 2012. Since we regularly mention user’s twitter handles in our post content, it only made sense to come up with a way to automatically link twitter usernames in WordPress. Instead of relying on a third-party script, we decided to write a short and simple plugin to take care of the job. In this article, we will show you how to automatically link twitter usernames in WordPress when you mention it after the @ sign like so: @wpbeginner.

All you have to do is open a blank .php file and call it wpb-twitlinks.php. Then copy the code below and save it in there. Upload the file into your plugins folder, and simply activate the plugin.

01 <?php
02 /*
03 Plugin Name: WPB Linkify Twitter Usernames
04 Description: Automatically link Twitter usernames in WordPress
05 Author: Syed Balkhi
06 Author URI: http://www.wpbeginner.com
07 */
08
09 function twtreplace($content) {
10     $twtreplace = preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/',"$1<a href=\"http://twitter.com/$2\" target=\"_blank\" rel=\"nofollow\">@$2</a>",$content);
11     return $twtreplace;
12 }
13
14 add_filter('the_content', 'twtreplace');  
15
16 //For Comments props to Julien Maury
17 add_filter('comment_text', 'twtreplace');
18
19 ?>

Note, since we only use this on our single post and pages, we only have the filter for the_content. You can always extend this feature to excerpts as well by adding the following line:

1 add_filter('the_excerpt', 'twtreplace');

We are not saying that this is the only method that exists. There probably are bunch of jQuery solutions available. This is the fastest and most effective solution in our opinion.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s