Make a Little House

RSS
Nov 4

Facebook Share-count Tooltip Using PHP and jQuery/qTip.

For a recent project, I needed a way to show Facebook share counts on a huge number (potentially thousands) of URLs. jQuery to the rescue with help from a plugin sidekick, qTip.

qTip quickly allows you to add tooltips or popup boxes. All you do is call the qtip action on a jQuery selector, and you’re in business. It also lets you call pages dynamically to use as content for the tooptip. And that’s exactly how I am using it here.

jQuery selector runs qTip on the links; qTip populates a tooltip by calling a PHP page; PHP requests Facebook share counts on the href associated with the link. Now, just by assigning that class name to any anchor element, you have a tooltip that shows how many times that link is shared on Facebook.

HTML:

<a href="http://wiki.developers.facebook.com/index.php/API" 
class="shared_link">Facebook API</a>

Javascript:

$(document).ready(function(){
$(".shared_link").each(function(){
$(this).qtip({
content: {
url: 'fetchfbshare.php',
data: {url: $(this).attr('href')},
method: 'post'
},
show: 'mouseover',
hide: 'mouseout'
});
});
});

PHP:

// Encode the URI
$uri = urlencode($_POST['url']);
// Request the stats
$r = file_get_contents('http://api.facebook.com/restserver.php?method=links.getStats&urls='.$uri);
// Parse the XML results
$xml = simplexml_load_string( $r );
// Format output
$shareCount = (string)$xml->link_stat[0]->share_count;
echo "Share Count: $shareCount";

View the sample or download the source. Download the qTip and jQuery libraries. qTip optionally will package them all up for you. The sample files look for the qTip and jQuery files in a /js subdir.

Just think of all the ways you can improve and improvise on this.