Family Encyclopedia >> Electronics

How to Automatically Link @Twitter Usernames in WordPress Posts and Comments

As WordPress experts at WPBeginner, we've powered sites mentioning countless Twitter handles. Two years ago, Twitter's Anywhere API made @mentions auto-link to profiles with hovercards. Sadly, it was retired on December 6, 2012. To keep linking @usernames like @wpbeginner seamlessly in our content, we crafted a lightweight, custom plugin—no third-party scripts needed.

Create a new file named wpb-twitlinks.php, paste the code below, upload to your /wp-content/plugins/ folder, and activate it. Done!

/*
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) {
return preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/', '$1<a href="https://twitter.com/$2">@$2</a>', $content);
}
add_filter('the_content', 'twtreplace');

// For comments (thanks to Julien Maury)
add_filter('comment_text', 'twtreplace');
?>

This targets post content and pages, but easily extend to excerpts:

add_filter('the_excerpt', 'twtreplace');

While jQuery options exist, this PHP solution is the fastest and most reliable we've tested across millions of WPBeginner visitors.