Automatically Replace Twitter Username With Link in WordPress

  • follow us in feedly
Published June 28, 2013 by Brad Knutson
Replace Twitter Username With Link in WordPress

Ever wonder how some sites allow you to enter a Twitter handle (preceeded by an @ symbol) and turn it into a URL directly to that users Twitter page? This is actually accomplished fairly easily with a little PHP, and can be quickly converted to a WordPress function.

Enter the below code directly into your themes functions.php file.

function twitter_replace($content) {
	$twitter_replace = preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/',"$1<a href=\"$2\" target=\"_blank\" rel=\"nofollow\">@$2</a>",$content);
	return $twitter_replace;
add_filter('the_content', 'twitter_replace');


These should work:


These should not work:

It works! Here’s how.

Twitter account pages always contain the exact Twitter username. They are not case sensitive, and are always in the same format:{twitter_handle}

Our function parses the WordPress post content (the content you enter into the Visual or Text editor on a page or post), searches for matches of a regular expression, and replaces any matches with the appropriate HTML to create an anchor tag wrapped around the original match. Did I confuse you yet? If you’re not familiar with PHP, all you need to know is that the function finds Twitter names, and replaces them with Twitter links.

The PHP function shown above has a little bit of error handling, as it does make sure to ignore solo @ symbols and any @ symbols preceded by text – such as in an email.

Pretty cool huh?

To take this a step further, you could extend this to account for Twitter usernames entered in the comments section by adding another filter at the end of your function:

add_filter('comment_text', 'twitter_replace');
The following two tabs change content below.
Founder at Inbounderish
Brad Knutson is a Web Developer in the Twin Cities area of Minnesota. He has experience working with WordPress and Drupal, and also has an interest in SEO and Inbound Marketing.

Keep Up-to-Date



See a complete list of topics discussed in blog posts here.

Check These Out

Get 2 Weeks Free! Sign Up Today! Premium Managed WordPress Hosting Genesis Framework for WordPress SEO is complex. Tools should be simple. Thesis Theme for WordPress:  Options Galore and a Helpful Support Community

One thought on “Automatically Replace Twitter Username With Link in WordPress

Share Your Thoughts

Your email address will not be shown.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">