Advertisement
Creative Coding

Custom Counter for Twitter and Feedburner

by

I would like to share a simple way to have your Twitter follower counter or Feedburner total reader counter using custom styling on your WordPress website. You can see some examples on Custom Counter Page to get the idea of how these counters can look. Enough with the introduction, lets get started.


Step 1 Reading the value

The most important thing is how can we read the value from Twitter and Feedburner, let start with Twitter first. You can get details for your Twitter account by visiting the following URL: https://twitter.com/users/show/insert-your-username-here For example https://twitter.com/users/show/eizil, if you click the URL, you will see a list of information regarding my Twitter account in XML format.

We can do a similar thing to Feedburner too, you can use the following URL to get your Feedburner data: https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=insert-your-username-here For example https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=eizil, if you click the URL, you will see information regarding my Feedburner account.

So now we have the source for our info, next we need to read the XML value from our website to be used in our custom counter. We will use file_get_contents and the SimpleXMLElement function to read the value from Twitter or Feedburner.

// read Feedburner data
            $data = file_get_contents("https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=insert-your-username-here);         
            $xml = new SimpleXMLElement($data);

// read Twitter data
            $data = file_get_contents ( 'http://twitter.com/users/show/insert-your-username-here');
            $xml = new SimpleXMLElement ( $data );

Now we have all the data we needed from Twitter and Feedburner, next we need to read the follower and reader value from this data.

           $total = $xml->feed->entry['circulation'];  // Read the total count from Feedburner
           $total = $xml->followers_count; // Read total follower count from Twitter

And we combine this code to get the totals for Twitter and Feedburner like the example below.

// read Feedburner data
            $data = file_get_contents("https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=insert-your-username-here);         
            $xml = new SimpleXMLElement($data);
            $total = $xml->feed->entry['circulation'];  // Read the total count from Feedburner
// read Twitter data
            $data = file_get_contents ( 'http://twitter.com/users/show/insert-your-username-here');
            $xml = new SimpleXMLElement ( $data );
            $total = $xml->followers_count; // Read total follower count from Twitter

Step 2 Styling the counter

We have our value for our counter already, next we will style our counter to be better looking. We will use the following HTML structure for our counter.

    
Value
value

For Style 1 in Custom Counter Page, we will use the following CSS:

.counter { float:left; clear:both; width: 100%; }
/* Feedburner counter */
#feedcount {  float: left;  position: relative;}
#feedcount a {  width: 150px;  height: 38px;  background: url(images/subscribe.png);  display: block; }
#feedcount span {  position: absolute;  top: 10px;  right: 15px;  color: white;  font-size: 0.75em;  font-weight: bold;}
/* Twitter counter */
#twitcount {  float: left;  position: relative;}
#twitcount a {  width: 150px;  height: 38px;  background: url(images/subscribe-twitter.png);  display: block;}
#twitcount span {  position: absolute;  top: 10px;  right: 12px;  color: white;  font-size: 0.75em;  font-weight: bold;}

Now you have a custom counter to be used on your WordPress theme.


Step 3 Get the code into theme functions

At this stage, we already know how to read the value and how to make a simple counter, next we will create a new function in our theme functions.php file to handle this request. We will also add a cache file to read this value, as we don't want the counter to try to fetch a new value each time a user visits our WordPress website.

Let's start with creating a new function named getTwitFeedburnCount() like the example below

function getTwitFeedburnCount() {

}

Next we will add two variables to the function to enable us to use this for Twitter and Feedburner, the two variables we are going to use would be 1. username, and 2. type of account. These two values will be used to determine which code will be used to fetch the value, and as an identifier for our cache file.

function getTwitFeedburnCount($username, $type) {

}

We will prepare the cache file at the beginning of the function, first we will try to see if there is a cache file available to be used or else we will fetch a new value from Twitter or Feedburner.

function getTwitFeedburnCount($username, $type){
    if($type == "feedburner"):
        $cfile = sys_get_temp_dir().'/e1z'. $type . md5 ( $username );
    elseif($type == "twitter"):
        $cfile = sys_get_temp_dir().'/e1z'. $type . md5 ( $username );            
    endif;

    if (is_file ( $cfile ) == false):
        $cfile_time = strtotime ( '1983-04-30 07:15' );
    else:
        $cfile_time = filemtime ( $cfile );
    endif; 

    $difference = strtotime ( date ( 'Y-m-d H:i:s' ) ) - $cfile_time;

    if ($difference >= 3600):   // set the interval before updating the cache in seconds
        //fetch new value code goes here
    else:
        //read from cache file
    endif;
}

All cache will be stored in temporary file system, this is to avoid any security breach if we are to use a folder within our theme or WordPress installation. Now we can add the code that actually processes the reading from Twitter and Feedburner.

function getTwitFeedburnCount($username, $type){
    if($type == "feedburner"):
        $cfile = sys_get_temp_dir().'/e1z'. $type . md5 ( $username );
    elseif($type == "twitter"):
        $cfile = sys_get_temp_dir().'/e1z'. $type . md5 ( $username );            
    endif;

    if (is_file ( $cfile ) == false):
        $cfile_time = strtotime ( '1983-04-30 07:15' );
    else:
        $cfile_time = filemtime ( $cfile );
    endif; 

    $difference = strtotime ( date ( 'Y-m-d H:i:s' ) ) - $cfile_time;

    if ($difference >= 3600):   // set the interval before updating the cache
        if($type == "feedburner"):

            $data = file_get_contents("https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$username);         
            $xml = new SimpleXMLElement($data);
            $total = $xml->feed->entry['circulation'];  // Read the total count from Feedburner

        elseif($type == "twitter"):

            $data = file_get_contents ( 'http://twitter.com/users/show/' . $username );
            $xml = new SimpleXMLElement ( $data );
            $total = $xml->followers_count; // Read total follower count from Twitter
         
        endif;

        if (is_file ( $cfile ) == true):
            unlink ( $cfile );
        endif;
            touch ( $cfile );
            file_put_contents ( $cfile, strval ( $total ) );
        return strval ( $total );

    else:
            $total = file_get_contents ( $cfile );
        return strval ( $total );
    endif;    
}

One thing I need to remind you, Feedburner sometimes resets the value if you fetch it live, and you end up having zero as the value for your reader. A quick solution for this would be to read the Feedburner value from 4 days ago. This is optional, just a solution if you ever encounter the problem like I did. You need to add the date to your function like shown below:

function getTwitFeedburnCount($username, $type){
    

    if($type == "feedburner"):
        $cfile = sys_get_temp_dir().'/e1z'. $type . md5 ( $username );
    elseif($type == "twitter"):
        $cfile = sys_get_temp_dir().'/e1z'. $type . md5 ( $username );            
    endif;

    if (is_file ( $cfile ) == false):
        $cfile_time = strtotime ( '1983-04-30 07:15' );
    else:
        $cfile_time = filemtime ( $cfile );
    endif; 

    $difference = strtotime ( date ( 'Y-m-d H:i:s' ) ) - $cfile_time;

    if ($difference >= 3600):   // set the interval before updating the cache
        if($type == "feedburner"):
        
            $date = date('Y-m-d', strtotime('-4 days'));
            $data = file_get_contents("https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$username."&dates=".$date.",".$date);         
            $xml = new SimpleXMLElement($data);
            $total = $xml->feed->entry['circulation'];  // Read the total count from Feedburner

        elseif($type == "twitter"):

            $data = file_get_contents ( 'http://twitter.com/users/show/' . $username );
            $xml = new SimpleXMLElement ( $data );
            $total = $xml->followers_count; // Read total follower count from Twitter
         
        endif;

        if (is_file ( $cfile ) == true):
            unlink ( $cfile );
        endif;
            touch ( $cfile );
            file_put_contents ( $cfile, strval ( $total ) );
        return strval ( $total );

    else:
            $total = file_get_contents ( $cfile );
        return strval ( $total );
    endif;    
}

After you finish adding this function to your theme, you are good to go.


Step 4 Use the code

Now if you want to use the function, please use the following format


echo getTwitFeedburnCount("insert-your-username-here", "feedburner");
echo getTwitFeedburnCount("insert-your-username-here", "twitter");

You can put the code together into the HTML like the example given below

    

Conclusion

By now you should be able to use this function in any of your themes, you can download the source file to take a look at other styles as seen on the Custom Counter Page. Do share your custom counter with me especially if you create a new style for your theme.

Related Posts
  • Code
    Web Development
    Laravel Unwrapped: Session, Auth and CacheLaravel wide retina preview
    Join me as we learn how to use Laravel's component-based system, Illuminate. Additionally, we'll see how to utilize service providers, Laravel's manager system, the Session, Auth, and Cache components, and the Store, Guard, and Repository libraries.Read More…
  • Computer Skills
    App Training
    Alfred Workflows for Advanced UsersAlfred400
    Well, you made it to the advanced tutorial. Well done! Now for the real work. Alfred can be used to do some complicated things, including recursive programming! The concepts here are not easy and not for the inexperienced programmer.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    PHP
    25 Laravel Tips and TricksCode
    There was a period of time, not too long ago, when PHP and its community were, for lack of better words, hated. Seemingly, the headline joke of every day was one that related to how terrible PHP was. Let's see, what new PHP-slamming blog article will be posted today?Read More…
  • Code
    Creative Coding
    A Look at the WordPress HTTP API: A Practical Example of wp_remote_getDiagram http api
    In the last article in this series, we took a look at the PHP functions that are available for making remote requests. Specifically, we reviewed: file_get_contents cURL And we also discussed the WordPress function wp_remote_get. In this article, we're going to put the wp_remote_get to work. This function is part of the HTTP API - to practical use by using it to retrieve the following two things: The number of followers we have on Twitter Our most recent Tweet The nice thing is that we won't need to use any OAuth or authentication mechanisms, and we'll only need to take advantage of Twitter responses and PHP's JSON functionality. So in this article, we're going to take a practical look at how to do exactly this, then we'll end the series reviewing all of the information that wp_remote_get returns so that we'll know how to properly handle it in future work.Read More…
  • Code
    Tools & Tips
    HTTP: The Protocol Every Web Developer Must Know - Part 2Http
    In my previous article, we covered some of HTTP's basics, such as the URL scheme, status codes and request/response headers. With that as our foundation, we will look at the finer aspects of HTTP, like connection handling, authentication and HTTP caching. These topics are fairly extensive, but we'll cover the most important bits.Read More…