Thursday, November 28, 2013

Display Twitter Followers Count and More

There are widgets that display Twitter followers count, but those are limited and ugly. You can use this function to customize the way your twitter followers count look on your blog. Simply paste the code below:


function rarst_twitter_user( $username, $field, $display = false )

$interval = 3600;

$cache = get_option(‘rarst_twitter_user’);

$url = ‘http://api.twitter.com/1/users/show.json?screen_name=’.urlencode($username);


if ( false == $cache )

$cache = array();


// if first time request add placeholder and force update

if ( !isset( $cache[$username][$field] ) )

$cache[$username][$field] = NULL;

$cache[$username]['lastcheck'] = 0;


// if outdated

if( $cache[$username]['lastcheck'] < (time()-$interval) )


// holds decoded JSON data in memory

static $memorycache;


if ( isset($memorycache[$username]) )

$data = $memorycache[$username];


else

$result = wp_remote_retrieve_body(wp_remote_request($url));

$data = json_decode( $result );

if ( is_object($data) )

$memorycache[$username] = $data;


if ( is_object($data) )

// update all fields, known to be requested

foreach ($cache[$username] as $key => $value)

if( isset($data->$key) )

$cache[$username][$key] = $data->$key;


$cache[$username]['lastcheck'] = time();


else

$cache[$username]['lastcheck'] = time()+60;


update_option( ‘rarst_twitter_user’, $cache );


if ( false != $display )

echo $cache[$username][$field];

return $cache[$username][$field];


Then place the following code where you want to display the count in your theme file:


echo rarst_twitter_user(‘wpbeginner’, ‘name’).’ has ‘.

rarst_twitter_user(‘wpbeginner’, ‘followers_count’).’ followers after ‘.

rarst_twitter_user(‘wpbeginner’, ‘statuses_count’).’ updates.’;



Display Twitter Followers Count and More

No comments:

Post a Comment

Please mention your comments.......