Looking for an easy way to include your current Twitter count in WordPress? Here’s a simple piece of code I’m using to fetch and display the current Twitter count, it includes transient caching of one hour for your most recent Twitter count.
/**
* Summary returns the current follower count of a specific Twitter account, or FALSE if not found
* @param String $twitter_username the username you wish to get a Twitter count for
* @param Number $transient_cache the time in seconds to cache the transient (default is one hour)
* @return String an unformatted number of followers from twitter
*
* @author Christopher Ross (@thisismyurl)
* @version 1.0.0
*/
function thisismyurl_twitter_count( $twitter_username = 'thisismyurl', $transient_cache = 3600 ) {
$current_twitter_count = get_transient( 'thisismyurl_twitter_count' );
if ( empty( $current_twitter_count ) ) {
$xml = file_get_contents ( 'http://twitter.com/users/show/' . $twitter_username );
if ( $xml ) {
$twitter_profile = new SimpleXMLElement ( $xml );
$current_twitter_count = $twitter_profile->followers_count;
if ( !empty( $current_twitter_count ) )
set_transient( 'thisismyurl_twitter_count' , $current_twitter_count, $transient_cache );
} else {
return FALSE;
}
}
return $current_twitter_count;
}
To display your current Twitter count in your WordPress theme, include the code:
if ( function_exists( 'thisismyurl_twitter_count' ) ) echo thisismyurl_twitter_count( 'thisismyurl', 3600 );
If the count can not be returned, the function will return FALSE which allows error checking such as:
if ( function_exists( 'thisismyurl_twitter_count' ) ) {
$twitter_count = thisismyurl_twitter_count( 'thisismyurl', 3600 );
if ( $twitter_count )
echo 'Twitter Count:' . $twitter_count;
}
What do you think? Is there a way to improve this function?