Post Pic

Display the total number of your Twitter followers on your WordPress blog

If you’re on Twitter, you probably display the number of your followers on your blog, using the chicklet from TwitterCounter.com. Today, I’m going to show you how to display your followers in full text mode.

The first thing to do is to paste the following php functions on the functions.php file from your WordPress blog theme:

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;
}

Then, simply paste the following anywhere on your theme files. Just replace my username with yours.

<?php echo getFollowers("catswhocode")." followers"; ?>

Related Posts

Related Posts

No related posts.

4 Responses

Aug 16 2011 03:23

Hi

I guess you are not aware of twitters api. There is no need for such long code.

See this: http://api.twitter.com/1/users/show.json?screen_name=

It returns a json object which you can use to get the followers count.

Here, the count is stored in ‘followers_count’

Nov 11 2011 19:35

Great bit of coding, thanks

Jan 18 2012 10:11

this is the worst method I have ever seen.

Feb 07 2012 19:18

i am not experienced coder m looking for some simple widget
thanks

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox