Add Hashtag Links to your WordPress Twitter Archive

TwitterShayne Sanderson’s excellent article teaches you how to create a Twitter archive of your very own using WordPress. I used the instructions to create my very own archive here: @kworthington’s Twitter Archive.

The tutorial is great and got me exactly the result I was looking for. Except one thing. Hashtags that were linked to Twitter’s search, as indicated in Shayne’s article:

“The only thing that I notice is that hashtags are not links on imported tweets…I’m still researching that one, but if you know (or find) a way to do this, please feel free to comment and let me know!”

Important note: If you already have imported your tweets, this WILL create duplicate entries for tweets that have hastags! One tweet without the link (from your first import) and one tweet with the hashtag link(s). If you are creating the archive for the first time using my code below, you won’t have any duplicates. In fact, it is best to add my code FIRST, before doing any importing if at all possible.

OK, here’s how to do it:

Open up the plugin editor and select Twitter Importer, file name: twitter-importer/twitter-importer.php

Find the function called get_posts, and copy the lines from between the /* paste */ code below into the file.

function get_posts($importdata) {
global $wpdb;

set_magic_quotes_runtime(0);
$importdata = str_replace(array ("rn", "r"), "n", $importdata);

/* start of paste */

/* fix hashtags to be links */
$importdata= preg_replace('/(^|s)#(w*[a-zA-Z_]+w*)/', '1#<a href="http://search.twitter.com/search?q=%232">2</a>', $importdata);

/* end of paste*/

preg_match_all('|(.*?)|is', $importdata, $this->posts);

That’s it! Run the import, and all your hashtags will be linked to Twitter’s search.

If you liked this, please Tweet ThisTweet a link. Thanks!