Display The Number Of Your Twitter Followers in WordPress
So you have bazillions of followers on Twitter and you want to display your Twitter dominance to all the people who visit your blog huh? If you are not a fan of plugins you can display your follow count in plain text and style it to your liking later on.
Paste the following php code in the functions.php file from your WordPress blog theme…
[php]
function string_getInsertedString($long_string,$short_string,$is_html=false){
if($short_string>=strlen($long_string))return false;
$insertion_length=strlen($long_string)-strlen($short_string);
for($i=0;$i<strlen($short_string);++$i){
if($long_string[$i]!=$short_string[$i])break;
}
$inserted_string=substr($long_string,$i,$insertion_length);
if($is_html && $inserted_string[$insertion_length-1]==’<’){
$inserted_string=’<’.substr($inserted_string,0,$insertion_length-1);
}
return $inserted_string;
}
function DOMElement_getOuterHTML($document,$element){
$html=$document->saveHTML();
$element->parentNode->removeChild($element);
$html2=$document->saveHTML();
return string_getInsertedString($html,$html2,true);
}
function getFollowers($username){
$x = file_get_contents("http://twitter.com/".$username);
$doc = new DomDocument;
@$doc->loadHTML($x);
$ele = $doc->getElementById(‘follower_count’);
$innerHTML=preg_replace(‘/^<[^>]*>(.*)<[^>]*>$/’,"\\1",DOMElement_getOuterHTML($doc,$ele));
return $innerHTML;
}
[/php]
Once you have done this you simply paste the following anywhere on your theme files. Just replace “wpswitch” with your Twitter username.
[php]<?php echo getFollowers("wpswitch")." followers"; ?>[/php]
.via { WpRecipes }
Comment by The News Nation — April 13, 2011 @ 4:25 pm
Thanks for the awesome code. I was searching it on Google from last 2-3 months. You make my task easy, actually I’m using twitter and want to know the status of it on my blog. Thanks a lot for sharing with me.