Do you want to get your Facebook fan count and display it on your website? While there’s probably a plugin for this, we have created a quick code snippet that you can use to get Facebook fan count using wp_remote_get.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
function get_fan_count(){
$fb_id = '106900272716297';
$count = get_transient('fan_count');
if ($count !== false) return $count;
$count = 0;
$data = wp_remote_get('http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id='.$fb_id.'');
if (is_wp_error($data)) {
return 'whoa error!!!';
}else{
$count = strip_tags($data[body]);
}
set_transient('fan_count', $count, 60*60*24); // 24 hour cache
return $count;
}
Add this code snippet into your WordPress theme file where you want to display the Facebook fan count.
<? echo get_fan_count(); ?>
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 9 best WordPress help desk plugins for customer support and 50+ best WooCommerce themes for your online store.
Hi, great stuff! How would ony display the total count (FB + Twitter) using this method?
Everytimes it shows 616 counts in echo. My fanpage has 135k fans. I checked the the direct api url. It shows 135967
didn’t work for me 🙁 anyway thanks for sharing
[…] initially, you need to paste the following snippet into your functionality plugin (thanks to Kevin Chard for the basis of this […]
Awesome! Just what I was looking for…
Cool glad to help!