Convert links, username mentions, and hashtags in a tweet with PHP in WordPress

While working a recent project, we had a WP cron running that scraped Twitter and saved all the returned tweets as a custom post type. When displaying the tweet content, I realllly wanted to make the @username mentions, hashtags, and URLs auto-convert into proper links. Even if you aren’t make a silly webapp, there are still plenty of times when you might be displaying Twitter content.

In my hunt, I noticed WordPress has a built-in core function called make_clickable(). Like the name implies, it would scan the provided value and make all the URLs into clickable links. It worked just fine, but I also wanted user mentions and hashtags, so I went a step further and made my own function, aptly named make_twitter(). Check it out below:

<?php 
//place the following in functions.php or the like

function make_twitter($tweetcontent) {
  $tweetcontent = preg_replace("/[@]+([A-Za-z0-9-_]+)/", "\\0", $tweetcontent );
  $tweetcontent = preg_replace("/[#]+([A-Za-z0-9-_]+)/", "\\0", $tweetcontent );
  $tweetcontent = preg_replace("/((http)+(s)?:\/\/[^<>\s]+)/i", "\\0", $tweetcontent );
  return $tweetcontent;
}

//then use the function in your templates like so:

echo make_twitter(get_the_content());

What it does is actually pretty simple. First, place the make_twitter() function into your functions.php file (or wherever you're stashing your functions). Next, use make_twitter() in your templates. All you've gotta do is provide the tweet content, in this case my post content, so I use get_the_content().

Once my function receives the tweet, it simply runs a couple of regular expressions to sniff out the usernames, hashtags, and URLs, replacing them with proper links. On my project, I even changed the user link to the local site profile (since our accounts mirrored the Twitter account namespace).

One thought on “Convert links, username mentions, and hashtags in a tweet with PHP in WordPress