Render your Twitter followers count in your wordpress blog


/ Published in: PHP
Save to your folder(s)

Add this snippet to the functions.php to render your twitter followers count.
Replace 'planetabhi' with your twitter screen name


Copy this code and paste it in your HTML
  1. function my_followers_count($screen_name = 'planetabhi'){
  2. $key = 'my_followers_count_' . $screen_name;
  3.  
  4. // Let's see if we have a cached version
  5. $followers_count = get_transient($key);
  6. if ($followers_count !== false)
  7. return $followers_count;
  8. else
  9. {
  10. // If there's no cached version we ask Twitter
  11. $response = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name={$screen_name}");
  12. if (is_wp_error($response))
  13. {
  14. // In case Twitter is down we return the last successful count
  15. return get_option($key);
  16. }
  17. else
  18. {
  19. // If everything's okay, parse the body and json_decode it
  20. $json = json_decode(wp_remote_retrieve_body($response));
  21. $count = $json->followers_count;
  22.  
  23. // Store the result in a transient, expires after 1 day
  24. // Also store it as the last successful using update_option
  25. set_transient($key, $count, 60*60*24);
  26. update_option($key, $count);
  27. return $count;
  28. }
  29. }
  30. }
  31.  
  32. echo "I have " . my_followers_count('planetabhi') . " followers";

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.