Skip to content

Instantly share code, notes, and snippets.

@ihorvorotnov
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ihorvorotnov/9132767 to your computer and use it in GitHub Desktop.
Save ihorvorotnov/9132767 to your computer and use it in GitHub Desktop.
WordPress - Twitter followers and Facebook fans count with transients
/**
* Other transients stuff here http://www.catswhocode.com/blog/wordpress-transients-api-practical-examples
*/
function my_followers_count($screen_name = 'kovshenin'){
$key = 'my_followers_count_' . $screen_name;
// Let's see if we have a cached version
$followers_count = get_transient($key);
if ($followers_count !== false)
return $followers_count;
else
{
// If there's no cached version we ask Twitter
$response = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name={$screen_name}");
if (is_wp_error($response))
{
// In case Twitter is down we return the last successful count
return get_option($key);
}
else
{
// If everything's okay, parse the body and json_decode it
$json = json_decode(wp_remote_retrieve_body($response));
$count = $json->followers_count;
// Store the result in a transient, expires after 1 day
// Also store it as the last successful using update_option
set_transient($key, $count, 60*60*24);
update_option($key, $count);
return $count;
}
}
}
echo "I have " . my_followers_count('kovshenin') . " followers";
/**
* Facebook page fans count.
* Add transients manually.
*/
<?php
$page_id = "YOUR PAGE-ID";
$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
echo $fans;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment