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

Posted: December 27, 2012 in social
Tags: ,

Twitter Follower Count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.

1
<?php echo twitter_count(); ?>

Facebook Like Count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function fb_count(){
         $fb_id = '291541550876794';
         $count = get_transient('fb5_count');
    if ($count !== false) return $count;
         $count = 0;
   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.

1
<?php echo fb_count(); ?>

Google+ Circle Count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function gplus_count(){
         $count = get_transient('gplus_count');
    if ($count !== false) return $count;
         $count = 0;
   if (is_wp_error($data)) {
         return 'whoa error!!!';
   }else{
        $match = preg_match('/<strong>(.*?)<\/strong>/s', $data, $results);
        if ( isset ( $results ) && !empty ( $results ) )
                {
                        $count = $results[1];
                }
        }
set_transient('gplus_count', $count, 60*60*48); // 72 hour cache
return $count;
}

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

1
<?php echo gplus_count(); ?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s