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.
<?php /* Plugin Name: WPB Linkify Twitter Usernames Description: Automatically link Twitter usernames in WordPress Author: Syed Balkhi Author URI: https://www.wpbeginner.com */ function twtreplace($content) { $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); return $twtreplace; } add_filter('the_content', 'twtreplace'); //For Comments props to Julien Maury add_filter('comment_text', 'twtreplace'); ?>
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:
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.
nice code! is there something similar for twitter # hash tags that will link to those on twitter as well?
Just want to share cool tip. If you want to add some interactivity use web intents. It’s really easy : just add intent/user?screen_name= before $2 (in href) and enjoy !
This is very useful tips.
But, what happened to @username that already has a link to twitter?
Hmm not sure. It should work.
You could also add :
add_filter(‘comment_text’, ‘twtreplace’);
to get the same in the comment section
Great tip, updating the post now
Thanks for this filter, another tweak I will keep in mw WP toolbox.
But there’s twitter Anywhere feature that do the job as well, and also adds some direct follow or twitter card as well. Very usefull and already integrated in some WP plugins.
Not sure if you read the article. Twitter is shutting off their Anywhere API on Dec. 6th. This is why we wrote this filter.
Well done! Im glad people make these plugins for twitter
THANKS!!! This is awesome of you to do for everyone!