Last active
March 26, 2019 15:55
-
-
Save itzmekhokan/2a91fe5ca7576228352c851ecff78408 to your computer and use it in GitHub Desktop.
Display Twitter Followers Counts and More in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_twitter_user_data( $username, $field, $display = false ) { | |
$interval = 3600; | |
$cache = get_option('get_twitter_user_data'); | |
$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( 'get_twitter_user_data', $cache ); | |
} | |
if ( false != $display ) | |
echo $cache[$username][$field]; | |
return $cache[$username][$field]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment