How to Get Your Twitter, Facebook, and Google+ Fan/Follower Count in PHP and WordPress

The code snippets below will provide you a function that you can echo anywhere on your site, to get the count for each social service. The snippets below will let you get your Twitter follower count, your Facebook like count, and your Google+ circle count.

Let’s take a look at the code.

Twitter Follower Count

function twitter_count(){
         $count = get_transient('twitter_count');
    if ($count !== false) return $count;
         $count = 0;
         $dataOrig = file_get_contents('http://twitter.com/users/show/wpforce');
   if (is_wp_error($dataOrig)) {
         return 'Error!!!';
   }else{
         $profile = new SimpleXMLElement ( $dataOrig );
		 $countOrig = $profile->followers_count;
		 $count = strval ( $countOrig );
		 }
set_transient('twitter_count', $count, 60*60*24); // 24 hour cache
return $count;
}

To use this function, simple echo it wherever you want it.

<?php echo twitter_count(); ?>

Facebook Like Count

function fb_count(){
         $fb_id = '291541550876794';
         $count = get_transient('fb5_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 'Error!!';
   }else{
        $countOrig = strip_tags($data[body]);
	$count = preg_replace('/\s+/','',$countOrig); // strip whitespace
   }
set_transient('fb5_count', $count, 60*60*24); // 24 hour cache
return $count;
}

To use this function, simple echo it wherever you want it.

<?php echo fb_count(); ?>

Google+ Circle Count

function gplus_count(){
         $count = get_transient('gplus_count');
    if ($count !== false) return $count;
         $count = 0;

        $data = file_get_contents('https://plus.google.com/+JonathanDingman/posts');

   if (is_wp_error($data)) {
         return 'whoa error!!!';
   }else{

        if (preg_match('/>([0-9,]+) people</i', $data, $matches)) {
                $results =  str_replace(',', '', $matches[1]);
        }

        if ( isset ( $results ) && !empty ( $results ) )
                {
                        $count = $results;
                }
        }
set_transient('gplus_count', $count, 60*60*48); // 72 hour cache
return $count;
}

To use this function, simple echo it wherever you want it.

<?php echo gplus_count(); ?>

Props to Andrew in the comments for commenting with a fix for this.


REMINDER The functions above use the set_transient() function which is built into WordPress, but you could swap out that function to use local disk cached files if you need to use this outside of WordPress.

UPDATE – 04/12/2012: Google+ changed it’s design and the code, so there was a small tweak to the G+ code. It now uses widgetsplus.com as the source, because the Google+ code became unreliable. Hat tip to Pedro for suggesting the new regex.
Each function is hard coded to use my username data, so you’ll want to adjust it to use your own data.

If you have any feedback or questions about the functions, please leave a comment below.

Comments

  1. By Ralf on

    Hi!
    That’s exact what I’m looking for. Works great in WordPress.
    Please help me to get this outside WordPress.
    I read your “Reminder”, but I don’t know how to “swap out that function to use local disk cached files”. Could you please post a code, that works php only?
    Thanks
    Ralf

    Reply »

    • By Jonathan Dingman on

      Hi Ralf,

      The focus of this site is more about WordPress, rather than building functions that work for any platform. Sorry, I won’t be developing the code to work outside of WordPress.

      Try doing a google search for “caching files php” and see what you can come up with, there are plenty of great resources out there that will teach you how to do it.

      Just swap out the set_transient() function for the caching call once you have the file caching layer in place.

      Reply »

  2. By on

    Get circles count in that way don´t work anymore…. Google plus has changed the accounts layout and the circles count is now loaded by Javascript in new account layout. Plus API doesn’t share user circle count. The only way I think is catch the Circle Count that is in the “plus widget” (http://widgetsplus.com/). What do you think about it ?

    Reply »

    • By Jonathan Dingman on

      I’ll look at it and see what needs to be done, I can probably whip something up. Thanks for the heads up.

      Reply »

      • By on

        Don’t worry, your code worked since 1 or 2 weeks ago. But now it doesn’t, either for me (my own code). I archive a solution that works with the Google plus widget from Google (http://widgetsplus.com/):

        $datos_plus = file_get_contents(‘http://widgetsplus.com/google_plus_widget.php?pid=’.$googlePlusID);
        preg_match(‘/<strong>(.*?)<\/strong>/s’, $datos_plus, $coincidencias);
        $circulos = $coincidencias[1];
        echo $circulos;

        This will works for a long time (until Google change the widget layout :P), you can change a litte the code for cache etc…

        Reply »

  3. By on

    Hey Pedro, nice one but how are you displaying just the count? When I use the widgetsplus.com script in my code it’s displaying the whole box and not just the count. Be great if you could help.

    Reply »

    • By Jonathan Dingman on

      That’s what the preg_match is for.

      I updated the code on the page to reflect what we’re using here on wpforcecom.wpengine.com, give it a try.

      Reply »

  4. By Sam Turner on

    Pretty new to all this, I’ve been looking at a way to convert the counts into a number format, but don’t seem to be having much look any tips on how to use the number_format method for larger counts.

    ta

    Reply »

  5. By Ludy on

    Hi!
    The http://widgetsplus.com seems to be offline … any new solution to get the number of circles ?

    best greetings

    Reply »

    • By Jonathan Dingman on

      Looks like http://www.circlecount.com/ might fit the bill. I’ll try to do some research soon and see if I can find a new solution that works within PHP.

      Reply »

  6. By Tushar Thakur on

    I want to dispaly alexa rank of my own website in the page (Only one page not throughout) SO please help me how can i insert the code, I mean where I should insert the code and how to call in in wordpress ?

    Reply »

    • By Jonathan Dingman on

      After a quick search, I found this page that should help you with that.

      Reply »

      • By Tushar Thakur on

        Thank you, I knwo the code but how to do it in wordpress, leave about alexa suppose I want to display the FB likes of my own URL on a post on my blog, how can I do it? I mean where to put that php codes?

        Reply »

        • By Jonathan Dingman on

          You would need to modify the code and put it in your functions.php file within your theme.

          Reply »

  7. By Willem on

    Hi, great! I got it working except for Google. Is there any way to get this work?

    Kind regards Willem

    Reply »

      • By Jonathan Dingman on

        Hi Willem,

        I’m not sure what you mean by your comment. What about Google? What issues are you having?

        Reply »

        • By Willem on

          Hi Jonathan,

          It just doens’t work while Facebook and Twitter do…
          Do you have the same experience?

          Kind regards,

          Willem

          Reply »

  8. By on

    The google+ code doesn’t work for me so I used this:

    $page = file_get_contents(‘https://plus.google.com/109666188313949283726’);
    if (preg_match(‘/>([0-9,]+) people</i', $page, $matches)) {
    return str_replace(',', '', $matches[1]);
    }

    The above skims the number of followers off the public G+ page so could break if they redesign the site. I have set up a Gist to cover G+ and other social networks which I'll keep up to date if this breaks: https://gist.github.com/andrewspear/6348709

    Reply »

    • By Jonathan Dingman on

      Thank you!

      I updated the post with your recommended code after some testing. Seems to work smoothly and caches nicely. The code could probably use some cleaning up even further, but it should definitely get the job done now.

      Cheers!

      Reply »

  9. By on

    Found this post thanks to Devesh from WPKube.

    Well written and great information! Something I was looking for and thank you so much!

    Gonna try adding the codes right now :)

    Reginald

    Reply »

  10. By on

    Here’s a one-liner that will also fetch your YouTube subscribers or total channel views:

    $youTubeSubscribers = json_decode(file_get_contents(‘http://gdata.youtube.com/feeds/api/users/mylittlegk?v=2&alt=json’))->entry->{‘yt$statistics’}->subscriberCount;

    $youTubeViews = json_decode(file_get_contents(‘http://gdata.youtube.com/feeds/api/users/mylittlegk?v=2&alt=json’))->entry->{‘yt$statistics’}->totalUploadViews;

    (via https://gist.github.com/andrewspear/6348709)

    Reply »

Trackbacks

  1. […] code (designed for WordPress, but easily modified) that will allow you to retrieve your counts: http://wpforce.com/twitter-facebook-googleplus-fan-follower-count-php/. You can then store the counts however you […]

  2. […] code (designed for WordPress, but easily modified) that will allow you to retrieve your counts: http://wpforce.com/twitter-facebook-googleplus-fan-follower-count-php/. You can then store the counts however you […]

Leave a Reply

Your email address will not be published. Required fields are marked *