How to Show Twitter follower count in text – WordPress

The Twitter buttons are great but they require JavaScript request every time a visitor hits your site. On top of that it's just slow.

One nice way to show your Twitter follower count is to do it in plain text. It's faster and you can style it according your theme.

Transients API

This functions uses the WordPress Transients API which allows you to save the value on the database.

The value gets stored for certain amount of time. Meaning, if someone visits your site within this period of time it will serve it from the database, avoiding the request to Twitter servers.

functions.php

Paste this function inside the functions.php file of your theme.

Modify with your own Twitter handle.

function my_followers_count($screen_name = 'ricard_dev'){
	$key = 'my_followers_count_' . $screen_name;

	$followers_count = get_transient($key);
	if ($followers_count !== false)
		return $followers_count;
	else
	{
		$response = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name={$screen_name}");
		if (is_wp_error($response))
		{
			return get_option($key);
		}
		else
		{
			$json = json_decode(wp_remote_retrieve_body($response));
			$count = $json->followers_count;

			set_transient($key, $count, 60*60*24);
			update_option($key, $count);
			return $count;
		}
	}
}Code language: PHP (php)

Anywhere your theme

Call the function anywhere in your theme.

echo "I have " . my_followers_count('ricard_dev') . " followers";Code language: PHP (php)

Leave a Reply

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