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.


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("{$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)

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> if you need to.