Within the past couple of years, Twitter has definitely evolved from a status update service to a way to engage with one another, with businesses, and with customers. For many (including us), it’s a way to notify your followers that you’ve published something new.
TweetMeme is arguably the most common choice when it comes to showing how many times your content has been retweeted and although there’s plenty of plug-ins that can offer this functionality for you, sometimes it’s more fun to build some stuff yourself (especially when it will scale to any theme).
Let’s do this.
We’re going to be editing a couple of the core files of your WordPress theme. Yes, there are a variety of ways to do this; however, we’ll be doing so from within the WordPress Theme Editor.
Login to WordPress and navigate to the Theme Editor. Open up functions.php and scroll to the bottom of the file.
The following function will accept a URL as an argument, request an XML response via the TweetMeme API, and then echo the number of times the given URL has been retweeted as tabulated by TweetMeme:
function tweetmeme_counter($url) {
// request the number of times this URL has been retweeted
$content = file_get_contents("http://api.tweetmeme.com/url_info?url=" . $url);
$xml_element = new SimpleXmlElement($content);
$num_retweets = $xml_element->story->url_count;
// set the value to 0 if the url_count is null
if(!$num_retweets) {
$num_retweets = 0;
}
// echo the HTML
echo '
';
}
Next, open up single.php and locate a place in the file that you’d like to display the retweet count. Pass the current post’s ID to the function we just created:
post_id)); ?>
If you’re interested in expanding the functionality, check out the TweetMeme API. Also note that you can always write out more HTML than demonstrated in our function. Providing other information, such as an element classname or or element ID, will make it easy to style using CSS.
Cool?
[HT: Gunnard]
Darren says
Even better – make it so you don’t have to add the tweetmeme_counter() function to your theme…
function add_tweetmeme_counter($content) {
//to add counter after content in a post
$content .= tweetmeme_counter(get_permalink($post->post_id));
}
add_filter('the_content', 'add_tweetmeme_counter');
//to add to excerpts too
add_filter('the_excerpt', 'add_tweetmeme_counter');
Darren says
woops need an edit there – don’t forget to return $content.
function add_tweetmeme_counter($content) {
//to add counter after content in a post
$content .= tweetmeme_counter(get_permalink($post->post_id));
return $content;
}
add_filter('the_content', 'add_tweetmeme_counter');
//to add to excerpts too
add_filter('the_excerpt', 'add_tweetmeme_counter');
Tom says
Slick! Good stuff, Darren.