Site icon WP Smith

How to Display Only Twitter Messages with a Certain Hashtag

I see in a lot of places blogs about the ability to display their last tweet or tweets. However, I wanted to be able to display tweets that come from a specific user using a specific hashtag. So let's say anytime @bob wanted to tweet something with #somehash, the following PHP code will allow you to display just those tweets in WordPress. So you first need to decide (1) how many of the last tweets that you want to display ($count), (2) whether to hide replies, and (3) then what hashtag you would like to display (with or without the #).

I am working this into a twitter widget plugin.

[php]
$twitter_count= 5; //Set this to the number of tweets you want to display
$yourhashtag = 'myhashtag'; //Set this to a chose hashtag with or without #
$yourtwitter_username='username'; //Set this to your username with or without @
$twitter_hidereplies=False; //If you want to hide them, change to: $twitter_hidereplies=True;

//do not change anything below this line
$twitter_usernameA= '@'.str_replace("@","",$yourtwitter_username);
$twitter_username= str_replace("@","",$yourtwitter_username);

$twitter = wp_remote_retrieve_body( wp_remote_request( 'http://twitter.com/statuses/user_timeline/'. $twitter_username.'.json?count=1' ) );
$json = json_decode($twitter);
$count=$json[0]->user->statuses_count;

$twitter = wp_remote_retrieve_body( wp_remote_request( 'http://twitter.com/statuses/user_timeline/'. $twitter_username .'.json?count='.$count ) );
$json = json_decode($twitter);
if( is_wp_error($twitter) ) {
$tweets[] = '<li>There was an error while attempting to contact the Twitter API. Please try again.</li>' . "n";
}
elseif( $json->error ) {
$tweets[] = '<li>The Twitter API returned an error while processing your request. Please try again</li>' . "n";
}
else
{
$hashtag = '#'.str_replace("#","",$yourhashtag);
// Build the tweets array
foreach( (array)$json as $tweet )
{
// don't include @ replies (if applicable)
if( $twitter_hidereplies && $tweet->in_reply_to_user_id )
continue;

// stop the loop if we've got enough tweets
if( $tweets[$twitter_count - 1] )
break;

//adds tweets if hashtag_only was selected
$pos = strpos($tweet->text,$hashtag);
if ($pos === false)
continue;
$timeago = sprintf('about %s ago', human_time_diff(strtotime($tweet->created_at)));
$timeago_link = '<a href="http://twitter.com/'.$twitter_username.'/status/'.$tweet->id.'" rel="nofollow">'.$timeago.'</a>';
$tweets[] = '<li>'. $tweet->text . ' <span style="font-size: 85%;">' . $timeago_link . '</span></li>' . "n";
}
foreach( (array)$tweets as $tweet ) {
echo $tweet;}
}

[/php]