Twitter Followers

Rarst submitted a piece of code that allows you to display the number of Twitter followers you have.

In this article, we’ll show you how to display the number of Twitter followers in WordPress using a more advanced and attractive code. Rarst donated another another script to this project.

Advertisements

Twitter Followers
Features

This function is not restricted to the number of followers. Any non-nested value supplied by the Twitter users/show API call can be retrieved.

 

It has two cache levels:

 

  • For $interval seconds, the query values are stored as an array in the database using WP options;
  • API replies are cached in memory, allowing you to query any number of fields without having to make several API requests.

 

Advertisements

This should be safe to use for multiplying values and users at the same time without causing the API limit to be exceeded.

Tutorial

To begin, open the functions.php file in your theme and paste the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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];
}

Usage
You can now use the code in any WordPress template file you choose after you’ve pasted the function. Simply paste the following code into your browser:

1
2
3
echo rarst_twitter_user('wpbeginner', 'name').' has '.
rarst_twitter_user('wpbeginner', 'followers_count').' followers after '.
rarst_twitter_user('wpbeginner', 'statuses_count').' updates.';

The above code will display something like this

Advertisements

Leave a Reply