How To Display Twitter counter in Text

Display Twitter Counter in Text is easily in WordPress with PHP code, all need to do just write down some PHP Script in our wordpress theme, we can write it on sidebar.php, footer.php, header.php or whatever we want to put on.

This code is similar with our previous tutorial about display FeedBurner counter in text, but we need to change some code, because the source is different, we still use file_get_contents() functions, this functions is the some function that we use to modified TimThumb Script to make it work on some server problem. So, let’s get started

Write down Display Twitter Counter in Text code below

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$twit =file_get_contents('http://twitter.com/users/show/USERNAME.xml');
$begin '<followers_count>'$end '</followers_count>';
$page $twit;
$parts explode($begin,$page);
$page $parts[1];
$parts explode($end,$page);
$tcount $parts[0];
if($tcount == '') { $tcount '0'; }
echo '<div><strong>'.$tcount.' </strong> Followers</div>';
?>

Replace USERNAME with your own USERNAME, example our Twitter username is @WPTricksNet (you can follow it if you want ;)

Display Twitter Followers in Text using Transients API

Write this code on your functions.php theme files and save it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function get_twitter_count() {
// first check the transient
$count = get_transient('follower_count');
if ($count !== false) return $count;
// no count, so go get it
$count = 0;
$data = wp_remote_get('<a href="http://api.twitter.com/1/users/show.json?screen_name=WPTricksNet" rel="nofollow">http://api.twitter.com/1/users/show.json?screen_name=WPTricksNet</a>');
if (!is_wp_error($data)) {
$value = json_decode($data['body'],true);
$count $value['followers_count'];
}
// set the cached value
set_transient('follower_count'$count, 60*60); // 1 hour cache
return $count;
}

Please notes, you need to change username on the request, we have put WPTricksNet, so you need to put your own username. Next, you need to put the code to call this functions on your sidebar.php or whatever you want put the counter.

1
<?php echo get_twitter_count(); ?>

If you want style the code you can make like this example

1
<div class="twcounter"><?php echo get_twitter_count(); ?></div>

And you need add some style on your style.css

1
2
3
4
5
.twcounter {
background#89B6F8;
padding10px;
color#194B96;
}

Useful Source:

http://codex.wordpress.org/HTTP_API

http://codex.wordpress.org/Transients_API