How to Count Facebook Fans in PHP

Update: There’s an new easier way of retrieving the fans count using the Graph API, covered here: Counting Facebook Fans in PHP: The Graph API Way

Not too tricky this one, but very handy as the social media world is developing extremely fast. It may not be too useful to publish the fan count of your facebook fan page if you’ve got less than a hundred or so, but as soon as you jump that high, it’s a good idea to show people that they’re not the only ones following you. Same applies to Twitter and other social media platforms.

The code is fairly simple if you’re familiar with the Facebook API, and even easier if you ever used the Facebook Client for PHP library, which makes tackles this issue in (literally) three lines of code and a simple FQL query. Don’t forget that in order to work with the Facebook platform, you’ll need an API key and secret. If you haven’t got a developer account, follow this guide to set it up.

That’s probably the most difficult part of this article. Once you have a dev account and the PHP client library, all you do is:

require_once('facebook/facebook.php');
$facebook = new Facebook('api_key','api_secret');
$fql = 'select fan_count from page where page_id = your_page_id;';
$result = $facebook->api_client->fql_query($fql);
$fb_fans = $result[0]["fan_count"];

Please note! that the code above is fine for the old version of the Facebook PHP Client. They released a new one which handles things a little bit differently, so here’s the code for the new version (tested in 2.0.4):

require_once('src/facebook.php');

$facebook = new Facebook(array(
  'appId'  => 'your_app_id',
  'secret' => 'your_app_secret',
  'cookie' => true,
));

$result = $facebook->api(array(
	'method' => 'fql.query',
	'query' => 'select fan_count from page where page_id = your_page_id;'
));

$fb_fans = $result[0]['fan_count'];

Replace api_key and api_secret with your own keys and secrets, replace your_page_id with the numerical ID of the page you’d like to quote. Also, if you’re unsure what is returned, then you should run a few checks on $result using print_r or var_dump.

Well.. That’s it! I just came across this issue last week and thought somebody might find it useful. Also note that in order to optimize the load time of your page, you should cache the result for some time, perhaps a day or two. Same applies to Twitter followers count and anything else you’re doing via public APIs (unless you’re using a javascript widget of course).

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

37 comments

  • I have a question… can that be used for fan count of pages you don't manage?
    If so, how do you get that page id ?

    Frederic

    • Fred, just visit the specific fan page, hover your mouse over the user pic and you'll find a link which contains id= .. ;)

      Cheers.

  • Hi

    I tried this out but I get a fatal error. Could you help me out?
    I created this function
    function getFans() {
    $facebook = new Facebook("xxxxx","xxxxx");
    $fql = 'select fan_count from page where page_id = xxxxx';
    $result = $facebook->api_client->fql_query($fql);
    $fb_fans = $result[0]["fan_count"];
    return $fb_fans;
    }

    Fatal error: Call to a member function fql_query() on a non-object in C:xampphtdocs…..functions.php on line 219

    • Karo, it seems that they released a new version of the php library. I've added the code for 2.0.4 above, thanks for reporting this.

  • Doesn't work. Same error as Karo Devos.

    This information appears to be out of date.

    • Aaron, you're right, as I already mentioned to Karo, the code that was first posted is incompatible with the new client library. I modified the post and added a new snippet for the newer version.

      Cheers!

  • I'm sorry but I don't get it especially about the secret key and the app id. Does that mean the count can only be shown within the FB app? How would I do it for a wordpress page? Sorry if the questions sound silly.

    • No, not inside the FB app, you can use it outside via the external API, but you have to register your website as an application to get the API keys in order to use it.

  • PERFECT !! I was looking for a solution since a fews days but it was because I used the old code (client_api->fql_query…) now with the new one ($facebook->api(array …) it's perfectly works !!! :D thanks to resolve my long long long researches

  • I've been trying to get this to work for about an hour now, and I'm sure the answer is right in front of me. I downloaded and placed the Facebook Client Library in my theme's folder, and also set up a new application (and filled in the ID and secret settings). Also placed the Facebook page ID. Everything seems like it should be working, but it isn't…

    Here's what I have (I'm not sure if it will display, the numbers are fake):

    /fb-sdk/src/facebook.php');

    $facebook = new Facebook(array(
    'appId' => '123lkj1gh123jh2',
    'secret' => '13hkjh12kjh1jkh',
    'cookie' => true,
    ));

    $result = $facebook->api(array(
    'method' => 'fql.query',
    'query' => '123019809'
    ));

    $fb_fans = $result[0]['fan_count'];
    ?>

    • Argh, downloaded the Graph API, too (v. 2.1.1), placed it in my theme folder (Theme Name > facebook.php). I then placed the snippet from Counting Facebook Fans in PHP: The Graph API Way in my footer.php, and used bloginfo('template_directory') to make sure it was loading the facebook.php file. I input the ID/secret keys, but it's still not working.

      [code]<? php require('<?php bloginfo('template_directory'); ?>/facebook.php');

      $facebook = new Facebook(array(
      'appId' => '12345678912345678',
      'secret' => '123456789123456789123456789',
      ));

      $mysite = $facebook->api('/mashable');
      echo 'MySite has ' . $mysite['fan_count'] . ' fans';
      ?>
      [/code]

    • Nick, send me some screenshots of your application settings on Facebook. Make sure you're displaying all the errors and let me know if there are any exceptions thrown.

      Also, that's with line 1 of your scripts? I've never seen any syntax like that before ;) Why don't you try a simple require('facebook.php'); ? The reason I'm asking is that bloginfo echoes the output instead of returning it, you should use get_bloginfo, then you should use concatenation instead of nested php tags which are invalid. So it's either require('facebook.php'); or require(get_bloginfo('template_directory') . '/facebook.php')); in your case.

      Hope that helped.

  • This tutorial is awesome and I was using it for a while, but suddenly a week or two ago, my fan count stopped showing up.

    Do you know if Facebook changed something in the way they handle their API or whatever?

    • Hey kovshenin!

      I've actually been using the update, I meant to comment on that post instead of this one. The update was working for me, but seems to have died. :(

      Dunno if it's just me or if Facebook changed something.

      -Adam

    • Adam, strange. Try downloading the new Facebook SDK for PHP. I'm unsure if they changed anything, but some of the old sites from my side are still working fine. Do you receive any specific error?

    • The fan count just isn't showing, it comes up blank. This is the function I'm using:

      // Get Facebook Fan Count
      function facebook_count() {
      require('facebook.php');

      $facebook = new Facebook(array(
      'appId' => '108063289236125',
      'secret' => '6ddd3c8a3d5d0395a85878fa38fa903b',
      ));

      $sixprizes = $facebook->api('/sixprizes');
      echo $sixprizes['fan_count'];

      }

      I downloaded and reuploaded a new facebook.php file and it still doesn't look like it's working. Probably something wrong on my end… I guess I'll have to look into it more. Thanks for the help. :)

    • hi adam, may i know where are you trying to output the code? is it on a wordpress or another cms?

      i'm using wordpress and i manage to make it work. if you're using cms, try putting the code inside the file where you want it to output.

    • Mattia, if the graph API doesn't give that out (although I don't see a reason why they wouldn't) then I guess there is no way to. Check out the follow up post on this.

  • Using the above code

    base_facebook.php,facebook.php total 3 files avail in src folder
    and getcount having the above code snippet
    when running the page getting the

    Notice: Undefined offset: 0 in C:wampwwwfacebookfacebooklikegetcount.php on line 17

    how it can be resolved

    awaiting for your reply

    Thanks,

  • Hello thanks for sharing it.

    I have a website with an huge numbers of like buttons, one on every article published.

    I want to know if there is a system to know if there is a system to monitor the "likes" on the whole website, and on only the single page.

    Do you know if it is possible?

    Thank you very much.

    • Not a programming question, you should consult the Facebook Developers forums/discussion groups, there's plenty of info there about the "like" button implementations.