WordPress: display the total number of Twitter followers and Facebook fans

WordPress: display the total number of Twitter followers and Facebook fans

How to display the total count of our Twitter followers and Facebook fans on WordPress.

After a series of tests on WordPress for displaying the total number of my Twitter followers and Facebook fans, I came up with two simple functions which make use of the WordPress Transient API to store the returned results for 24 hours (one day). These functions must be added to your functions.php theme file and used later in your theme.

To make them work, just add your Twitter username and Facebook page ID (remember: is a numeric string) as arguments of the functions presented below.

get_twitter_followers_count()

function get_twitter_followers_count($username = 'username') {

	$followers_count = get_transient('followers_count');
	
   	if ($followers_count !== false) {
    	return $followers_count . ' followers';
    }
    
    
	$followers_count = '';
    $url = 'http://twitter.com/users/show/' . $username . '.xml';
    $data = wp_remote_get($url);
    
    if(is_wp_error($data)) {
    
    	return 'Follow me on Twitter';
    
    } else {
    
    	$response = $data['body'];
    	$followers_tag = preg_match('#<followers_count>(.+)</followers_count>#', $response, $matches);
    	$followers_count = strip_tags($matches[0]);
    
    }
    
    set_transient('followers_count', $followers_count, 60*60*24);
	return $followers_count . ' followers';
}

Usage

<p><?php echo get_twitter_followers_count('yourusername');?></p>

get_facebook_fan_count()

function get_facebook_fan_count($id = '0123456789') {

         $count = get_transient('fan_count');
         
    	 if ($count !== false) {
    		return $count . ' fans';
    	 }
    	 
         $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='.$id.'');
         
   		 if (is_wp_error($data)) {
         	return 'Follow me on Facebook';
   		 } else {
         	$count = trim(strip_tags($data['body']));
   		 }
   		
   		
		set_transient('fan_count', $count, 60*60*24);
		return $count . ' fans';
}

Usage

<p><?php echo get_facebook_fan_count('03784958691240');?></p>