How to Get Facebook Likes Count without a Plugin and with no Additional Pageload Time
Want to display a custom “likes” count on your site like Mashable and lots of other sites do?
You could use a plugin for WordPress (which will bog down your site with additional Javascript and CSS) or the native buttons from Facebook and Google+ (which also add JS files that slow your site down).
Or you can throw this into your functions.php file (assuming you’re using WordPress):
// get Facebook like counts from FB's Graph
function update_facebook_likes($content) {
global $post;
$url_path = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$data = file_get_contents('https://graph.facebook.com/v2.2/?id='.$url_path.'&fields=share&access_token=277265972706313|E1pMfI4rkE1Zbb8w-7NgkAZhoaM');
$obj = json_decode($data);
$like_no = $obj->{'share'};
$like_no = $like_no->{'share_count'};
/*if ($like_no == null) {
$like_no = 0;
}*/
update_post_meta($post->ID, 'fb_likes_count', $like_no, true);
}
add_action('wp', 'update_facebook_likes');
function display_fb_likes() {
global $post;
$fb_likes_count = get_post_meta($post->ID, 'fb_likes_count', true);
if (!empty($fb_likes_count)) {
echo $fb_likes_count.' Likes';
} else {
echo 'Share';
}
}
Replace YOUR ACCESS TOKEN
with your actual Access Token. Here’s how to get one.
The first function, update_facebook_likes
grabs the values from Facebook and places them in a custom field called fb_likes_count
.
The second function display_fb_likes
is just another way to display them in a theme, if you’d like. Just add display_fb_likes()
anywhere you’d like in your theme.