WP-Mix

A fresh mix of code snippets and tutorials

Display Twitter count in plain text

Twitter’s constant changes make it necessary to update techniques for otherwise simple tasks such as displaying your Twitter count via PHP.

Here’s the latest way to display your Twitter count with WordPress. This technique uses WP’s built-in caching and error-checking functionality to return your Twitter follower count in plain text:

// display twitter count
function twitter_count(){
	$count = get_transient('twitter_count');
	if ($count !== false) return $count;
		$count = 0;
		$dataOrig = file_get_contents('http://twitter.com/users/show/perishable');
	if (is_wp_error($dataOrig)) {
		return 'Error!!!';
	} else {
		$profile = new SimpleXMLElement ( $dataOrig );
		$countOrig = $profile->followers_count;
		$count = strval ( $countOrig );
	}
	set_transient('twitter_count', $count, 60*60*24); // = 24 hour cache
	return $count;
}

Add this code to your theme’s functions.php file, and replace “perishable” with your Twitter username. Then to display your Twitter count in your theme (e.g., sidebar.php), add the following code:

<?php echo twitter_count(); ?>

Disclaimer: I didn’t write this code, and don’t know the actual source. If you know, contact me. Thanks.

★ Pro Tip:

USP ProSAC Pro