bioneural.net site preferences

Accessibility

Toggle width/ text size:

style

Default/Alternate

Suits visual impairment, mobile devices

Styling

Change the theme:

layout

Sorry, this option is not enabled

Link behaviour

Links with an icon are off-site:

links

Right-click any link to optionally open in a new window or tab


 

Latest tweets using SimplePie

It's taken me a while to warm to Twitter. I created the Quicklinks category on my blog for sharing things that didn't warrant a full post, but even that's too much effort sometimes—especially if it's just sharing a link. You might argue that's what bookmarking services like Digg and Delicious are for, but even then it's a multistep process. I've only recently become aware of just how well suited the Twitter API is to sharing links or updating your status message to multiple services with minimal effort. This post shares some PHP code to integrate your tweets within your WordPress blog, and code to simplify getting your WordPress posts into other people's tweets.

The interconnectedness of tweeting

A few examples:

  • I use the Twitter updater plug-in to notify Twitter of new posts on my WordPress blog.
  • Darkslide on my iPhone can post a Flickr image link via the iPhone Twitterrific app.
  • Most of my links are discovered in my preferred RSS reader NetNewsWire, which can send these to desktop Twitterrific (News menu).
  • The Twitter app for Facebook will update your Facebook status using your tweets.
  • Twitter offer an RSS feed which can be used in conjunction with the SimplePie PHP library to bring tweets to your WordPress blog.

This last example is the focus of this post. I will assume that you have already downloaded and correctly installed SimplePie for WordPress from here.

A SimplePie template for Twitter

Create a text file called tweets.tmpl containing the following:

<div class="simplepie tweets">
	{IF_ERROR_BEGIN}<p class="error">{ERROR_MESSAGE}</p>{IF_ERROR_END}
		{ITEM_LOOP_BEGIN}
		<p><span class="twit_date">{ITEM_DATE_UTC}</span><br />{ITEM_DESCRIPTION}<br /><a href="{ITEM_PERMALINK}">#</a></p>
		{ITEM_LOOP_END}
</div>

Upload this file to the following directory on your server:

/wp-content/plugins/simplepie-plugin-for-wordpress/templates/

Now for a little post-processing

Every tweet will be prefixed with your Twitter username which is a bit redundant, so you might want to strip that out. Credit to Ben Griffiths for this know-how. Create a text file called twit_strip.php containing the following (be sure to replace 'bioneural:' with your own username):

<?php

/**
 * STRIP USERNAME FROM TWITTER FEED
 *
 * This will strip out 'bioneural:' from {ITEM_DESCRIPTION}.
 *
 * If you don't want to do anything to the content, simply remove the function.
 */

// We MUST keep this classname.
class SimplePie_PostProcess
{
	// Function name MUST be the same as the template tag we're processing, all lowercase, and MUST accept a single string parameter.
	function item_description($s) {
		$s = str_replace("bioneural: ", "", $s);
		return $s;
	}
}

?>

Upload this file to the following directory on your server:

/wp-content/plugins/simplepie-plugin-for-wordpress/processing/

Resolving a Twitter feed bug

As noted here there is an unresolved bug that will cause a "There are no items in this feed." message to appear:

Twitter feeds are just fine the first time they're loaded and cached, but are missing some/all items when the cache expires and SimplePie tries to re-fetch the feed.

To counter this open simplepie.inc from the following directory:

/wp-content/plugins/simplepie-core/

Comment out lines 1583–86 (in version 1.1.1) like so:

// if (isset($this->data['headers']['last-modified']))
// {
// 	$headers['if-modified-since'] = $this->data['headers']['last-modified'];
// }

Displaying your latest tweets

I pasted this into the sidebar.php file of my WordPress theme:

<?php /* Latest tweets */ if ((function_exists('SimplePieWP')) and is_page("contact")) { ?>
<div class="sb-tweets"><h4>Latest tweets</h4>
	<a href="http://twitter.com/bioneural" title="bioneural's profile on Twitter" class="feedlink"><img src="<?php bloginfo('template_directory'); ?>/styles/bioneural/twitter.png" alt="Twitter" style="margin-right: 20px;" /></a>
	<span class="metalink"><a href="http://twitter.com/statuses/user_timeline/15629885.rss" title="Web feed for latest tweets by bioneural" class="feedlink"><img src="<?php bloginfo('template_directory'); ?>/styles/bioneural/twit-feed-16px.png" alt="Feed" /></a></span>
	<?php echo SimplePieWP(array('http://twitter.com/statuses/user_timeline/15629885.rss'), array('items' => 3, 'template' => tweets, 'processing' => twit_strip)); ?>
	<p class="simple-credit">Do it with <a href="http://simplepie.org" rel="external">Simplepie</a>
</div>
<?php } ?>

The first PHP block above just makes sure the SimplePie for WordPress plug-in is active and that the "Latest tweets" div will appear only on the "Contacts" page of my WordPress installation.

The second PHP block specifies the Twitter feed you want to use (presumably your own!) and in this case that we want to display 3 feed items using the "tweets" template (tweets.tmpl) and "twit_strip" (twit_strip.php) post-processing instructions we created above.

Tip: If you still see a "There are no items in this feed." message, try adding 'set_timeout' => 60 to the above array to increase the timeout interval (too short an interval may cause the feed not to be cached).

With appropriate styling in your CSS file you should end up with something like this:

tweets

All being well there is a "live" version here.

Your post in their tweets

We don't need SimplePie for this bit, just generic PHP. I based my code on a clever recipe from Jean-Baptiste Jung that generates a TinyURL in place of the default character-consuming permalink.

Firstly I added the following function to my theme's functions.php file, using the cURL alternative to file_get_contents():

// Create TinyURL for post to Twitter
function getTinyUrl($url) {
	$ch = curl_init();
	$timeout = 5;
	curl_setopt ($ch, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.$url);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	$tinyurl = curl_exec($ch);
	curl_close($ch);
	return $tinyurl;
}

In the WordPress loop (theloop.php in the K2 theme) I added the following code to the "Actions" area at the foot of each post:

<span class="socialtwit"><a href="http://twitter.com/home?status=Reading%20'<?php _e(urlencode(the_title_attribute('echo=0'))); ?>'%20@%20<?php $turl = getTinyUrl(get_permalink($post->ID)); echo $turl ?>" title="Tweet this"><img src="http://www.bioneural.net/wp-content/themes/k2bn/styles/bioneural/twitter.png" alt="Twitter" /></a> Twitter</span>

All the reader sees is a Twitter icon:

action.jpg

This icon is linked to a properly encoded URL such as this:

http://twitter.com/home?status=Reading%20'Desktop+refits+with+GeekTool+and+friends'%20@%20http://tinyurl.com/cs54je

With no effort at all the reader can tweet your post complete with a "Reading" prefix, title, and compact URL:

tweeted.jpg

9 responses to Latest tweets using SimplePie


  1. 1 David

    Check out Tweetie for the iPhone :)

  2. 2 Bruce

    @D Do you like it best because Gruber does ;-)

  3. 3 Ben Griffiths

    Thanks for the link back Bruce :) I've also updated my article with the fix you have! I couldn't find a fix when I wrote that, glad to see there is one now!

    Personally, I use twitterrific on the iPhone! Love that little app :)

  4. 4 Bruce

    No worries Ben—this kind of collaborative problem-solving is what I love most about the Internet! I've been seeing the "no items" message even with commenting out those lines in simplepie.inc, but increasing the timeout value (as you also did) seems to have resolved that.

    Hey, just noticed if you live in Yorks. and work in Notts. you likely drive past me on the M1 every day ;-) I'm currently studying in Sheffield, based in Chesterfield.

  5. 5 Ben Griffiths

    Hehe, yep, I probably do pass you! I now use a custom script to scan my twitter feed as it also works for my flickr feed to. All in one. Should be useful for others though still :)

  6. 6 BOK

    Retweet: Check out Tweetie for the iPhone :-)
    I'll stay with TwitterTools to fill up my blogspace due to lack in time to post and inspiration...

  7. 7 Rob

    I've not jumped on either the Twitter or the social bookmarking bandwagons myself. It makes me feel like an old curmudgeon, but oh well.

  8. 8 Bruce

    Curmudgeon Rob? I had to look that one up... ye Old English term, huh? I was a slow starter there too, put off I think by the inclusion of the word "social" (eew!). But actually Twitter especially is great for discovering interesting tidbits without having to read lengthy blog posts (like mine!) and also for sharing things that you can't be bothered writing at length about (the kids call it micro-blogging I believe).

  9. 9 Josh

    Thanks for that. I've had this setup on my site for some time, but I decided I would finally fix the Twitter RSS tonight. I found an article on the SimplePie site the other day about the twitter bug, but I didn't know exactly how to go about using their fix with the WordPress plugin. I guess I should've thought to look in the SP core first. Ohh well.

Something to say?

Comments may be moderated, are subject to spam filtering, and should be inoffensive and relevant to this post. Please disclose commercial interests.

Usable tags include <a href=""> <blockquote> <em>.