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: @pluginthemehub

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.pluginthemehub.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:

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.

Leave a Reply

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

error: Content is protected !!

Pin It on Pinterest

Add address