Tutorial Details
- Program: WordPress
- Version (if applicable): 3.0+
- Difficulty: Intermediate
- Estimated Completion Time: 30 - 45 minutes
In this tutorial, I’ll walk you through the steps of setting up a widget, its settings form, and displaying it on your site. At the end of the tutorial, you can download an example plugin to build from. Of course, you can apply this to your themes as well.
Step 1: TwitterRSS Stats Widget !
This plugin will help you to display your Twitter Followers & Rss Subscribers Stats.
As we increasingly depend on more and more social services, there rises the need to provide a simple way to let our website visitors take part of our diverse social presence. This plugin will help you to display your WordPress Blog/Site Twitter Followers & Rss Subscribers Stats at the desired sidebar in the WordPress Widgets.
Getting started
You should already have WordPress installed, either on your local machine or on a testing server. For this tutorial we will use the WordPress version 3.2 You should also have a theme that support widgets. You could use the default one or make a WordPress theme from scratch and widgetize it.
Widget name
The first task in creating a WordPress widget is to think about what the widget will do, and make a (hopefully unique) name for your widget. Check out Plugins and the other repositories it refers to, to verify that your name is unique; you might also do a Google search on your proposed name. The name can be multiple words.
Widget files
I will start by creating a folder widget-name in our wp-content/plugins/ directory, where WordPress stores all it’s plugins. It’s a good idea to always create a folder for your plugin, even if it consists only of 1 file, so you could add more files later. The next step is to create our main widget file widget-name.php. To make WordPress recognize it as a plugin we should add a specific header to it, that describes our widget.
In my plugin there are 2 folder css & images, one plugin .php file and readme.txt file.
The readme.txt contains information about your plugin and can come in handy when you submit your plugin WordPress SVN plugin repository. See the readme sample.Also check How To Improve Your WordPress Plugin’s Readme.txt

The Plugin Basics
The heart of a WordPress plugins is the below 2 functions (commonly called `hooks`):
- add_action ($tag, $func) documentation
- add_filter ($tag,$func) documentation
It is very important to know the difference between the above functions.
- add_action –> does an action at various points of WordPress execution
- add_filter –> does filtering the data (eg. escaping quotes before mysql insert, or during output to browser.
Refer to the WordPress Plugin API for more better understanding.
Plugin Information
Create TRRStats.php and in the first line, add this commented plugin information to your file.Save this php file,
- Place the plugin folder to WordPress > wp-content > plugins,
- Go to your WordPress admin > plugins and you will see the new plugin listed, waiting to get activated.

Step 2: Setting Up Our Widget
As i inform you before that in this tutorial we are creating simple plug-in that displays your Twitter Followers & Rss Subscribers Stats.The first thing we have to do is load our widget when necessary. WordPress provides the widgets_init action hook that will allow us to do this. This action hook is fired right after the default WordPress widgets have been registered.
we simply have to extend the preexisting WP_Widget class. So, the first step is creating a new class with a unique name.
class TRRWidget extends WP_Widget
{
Then, we’ll want to add our first function. This function will be what makes our widget unique to WordPress, and it’ll allow us to set up the widget settings. Note that the class name and first function name are the same. In this example this is TRRWidget.
function TRRWidget(){
$widget_ops = array('classname' => 'widget_hello_world', 'description' => __( "Twitter & RSS Social Stats") );
$control_ops = array('width' => 300, 'height' => 300);
$this->WP_Widget('helloworld', __('Twitter & RSS Social Stats'), $widget_ops, $control_ops);
}
Displaying the widget
The next function within our WP_Widget class will handle the display of the widget. This code might be a little confusing because we don’t know what it all means (we haven’t added the controls).
The goal here is to take the settings supplied by what the user selected for the widget and display the widget according to those values.
It’s also important to make sure you use the $before_widget, $after_widget, $before_title, and $after_title variables. These are provided by the theme and should not be hardcoded. How widgets are displayed should always be handled by the theme.
function widget($args, $instance){
extract($args);
$title = apply_filters('widget_title', $instance['title'] );
$rss_email = empty($instance['rss_email']) ? 'webdesignergeeks' : $instance['rss_email'];
$twitter = empty($instance['twitter']) ? 'webdesignergeek' : $instance['twitter'];
$rss = empty($instance['rss']) ? 'webdesignergeeks' : $instance['rss'];
/* Before widget (defined by themes). */
echo $before_widget;
/* Title of widget (before and after defined by themes). */
if ( $title )
echo $before_title . $title . $after_title;
global $wpdb;
$item_info = $wpdb->get_row("SELECT * FROM TRR_Stats WHERE id=1;");
$rss_email_f = $item_info->rss_email;
/*Solve RSS Date Prob*/
$Today=date('Y-m-d');
$NewDate=Date('Y-m-d', strtotime("-2 days"));//minus 2 days to date
$url = file_get_contents('https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri='.$rss_email.'&dates='.$NewDate);
preg_match( '/circulation="(d+)"/', $url, $matches );
if ( $matches[1] )
$rss_f = $matches[1] . "+ Subscribers";
else
$rss_f = "0";
$twit = file_get_contents('http://twitter.com/users/show/'.$twitter.'.xml');
preg_match( '/(d+) /', $twit, $matches );
if ( $matches[1] )
$twitter_f = $matches[1] . "+ Followers";
else
$twitter_f = "0";
echo '
';
echo $after_widget;
}
Making sure our widget is updated and saved
In this step, we’ll take each of our widget settings and save them. It’s a pretty simple procedure. We’re just updating the widget to use the new user-selected values.
Saving Widget Data to the Database -
Most WordPress Widgets will need to get some input from the site owner or blog users and save it between sessions, for use in its filter functions, action functions, and template functions. This information has to be saved in the WordPress database, in order to be persistent between sessions. There are two basic methods for saving Widget data in the database.
The $wpdb object can be used to read data from any table in the WordPress database, not just the standard tables that WordPress creates. For example to SELECT some information from a custom table called “mytable”, you can do the following.
myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );
WordPress Options -
This method is appropriate for storing relatively small amounts of relatively static, named pieces of data – the type of data you’d expect the site owner to enter when first setting up the Widget, and rarely change thereafter. Option values can be strings, arrays, or PHP objects (they will be “serialized”, or converted to a string, before storage, and unserialized when retrieved). Option names are strings, and they must be unique, so that they do not conflict with either WordPress or other Plugins. Here are function you will need to modify options.
add_option($name, $value); update_option($name, $new_value); delete_option($name); Create a custom database table
This method is appropriate for data associated with individual posts, pages, attachments, or comments — the type of data that will grow as time goes on, and that doesn’t have individual names. See Creating Tables with Plugins for information on how to do this.
function update($new_instance, $old_instance){
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['rss_email'] = strip_tags(stripslashes($new_instance['rss_email']));
$instance['twitter'] = strip_tags(stripslashes($new_instance['twitter']));
$instance['rss'] = strip_tags(stripslashes($new_instance['rss']));
global $wpdb;
$wpdb->insert( 'TRR_Stats', array(
'id' => 1,
'rss_email' => $instance['rss_email'],
'twitter' => $instance['twitter'],
'rss' => $instance['rss']
)
);
global $wpdb;
$wpdb->update( 'TRR_Stats',
array(
'rss_email' => $instance['rss_email'],
'twitter' => $instance['twitter'],
'rss' => $instance['rss']
),
array(
'id' => 1
)
);
return $instance;
}
Step 3: Creating Widget Controls or Settings
The reason the new widget class in WordPress is so cool is how easy it is to set up controls for your widgets. important things The get_field_id() and get_field_name() functions handle most of the dirty work, leaving us to concentrate on more like actually creating the widget. Take special notice of how these functions are used because it’ll make life much simpler for you.
First, we might want to set up some defaults. By setting up defaults, we can control what’s shown just in case the user doesn’t select anything.
function form($instance){
$instance = wp_parse_args( (array) $instance, array('rss_email'=>'webdesignergeeks', 'twitter'=>'webdesignergeek', 'rss'=>'webdesignergeeks') );
$rss_email = htmlspecialchars($instance['rss_email']);
$twitter = htmlspecialchars($instance['twitter']);
$rss = htmlspecialchars($instance['rss']);
?>
get_field_name('twitter') . '">' . ('Twitter:') . '
';
echo '
i.e: webdesignergeeks
';
echo '
';
echo '
i.e: webdesignergeeks
';
echo '
';
echo '
i.e: webdesignergeeks
';
}?>
Step 4: Finally The Whole PHP Code Is
tutorial.
* Author: Ajay Patel
* Author URI: http://ajayy.com/
*/
?>
' . "n";
}
function my_plugin_create_table()
{
global $wpdb;
if($wpdb->get_var("show tables like TRR_Stats") != 'TRR_Stats')
{
$sql = "CREATE TABLE TRR_Stats (
id mediumint(9) NOT NULL,
rss_email tinytext NOT NULL,
twitter tinytext NOT NULL,
rss tinytext NOT NULL,
UNIQUE KEY id (id)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
}
register_activation_hook( __FILE__, 'my_plugin_create_table' );
class TRRWidget extends WP_Widget
{
function TRRWidget(){
$widget_ops = array('classname' => 'widget_hello_world', 'description' => __( "Twitter & RSS Social Stats") );
$control_ops = array('width' => 300, 'height' => 300);
$this->WP_Widget('helloworld', __('Twitter & RSS Social Stats'), $widget_ops, $control_ops);
}
function widget($args, $instance){
extract($args);
$title = apply_filters('widget_title', $instance['title'] );
$rss_email = empty($instance['rss_email']) ? 'webdesignergeeks' : $instance['rss_email'];
$twitter = empty($instance['twitter']) ? 'webdesignergeek' : $instance['twitter'];
$rss = empty($instance['rss']) ? 'webdesignergeeks' : $instance['rss'];
/* Before widget (defined by themes). */
echo $before_widget;
/* Title of widget (before and after defined by themes). */
if ( $title )
echo $before_title . $title . $after_title;
global $wpdb;
$item_info = $wpdb->get_row("SELECT * FROM TRR_Stats WHERE id=1;");
$rss_email_f = $item_info->rss_email;
/*Solve RSS Date Prob*/
$Today=date('Y-m-d');
$NewDate=Date('Y-m-d', strtotime("-2 days"));//minus 2 days to date
$url = file_get_contents('https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri='.$rss_email.'&dates='.$NewDate);
preg_match( '/circulation="(d+)"/', $url, $matches );
if ( $matches[1] )
$rss_f = $matches[1] . "+ Subscribers";
else
$rss_f = "0";
$twit = file_get_contents('http://twitter.com/users/show/'.$twitter.'.xml');
preg_match( '/(d+) /', $twit, $matches );
if ( $matches[1] )
$twitter_f = $matches[1] . "+ Followers";
else
$twitter_f = "0";
echo '
';
echo $after_widget;
}
/*Plugin Update */
function update($new_instance, $old_instance){
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['rss_email'] = strip_tags(stripslashes($new_instance['rss_email']));
$instance['twitter'] = strip_tags(stripslashes($new_instance['twitter']));
$instance['rss'] = strip_tags(stripslashes($new_instance['rss']));
global $wpdb;
$wpdb->insert( 'TRR_Stats', array(
'id' => 1,
'rss_email' => $instance['rss_email'],
'twitter' => $instance['twitter'],
'rss' => $instance['rss']
)
);
global $wpdb;
$wpdb->update( 'TRR_Stats',
array(
'rss_email' => $instance['rss_email'],
'twitter' => $instance['twitter'],
'rss' => $instance['rss']
),
array(
'id' => 1
)
);
return $instance;
}
function form($instance){
$instance = wp_parse_args( (array) $instance, array('rss_email'=>'webdesignergeeks', 'twitter'=>'webdesignergeek', 'rss'=>'webdesignergeeks') );
$rss_email = htmlspecialchars($instance['rss_email']);
$twitter = htmlspecialchars($instance['twitter']);
$rss = htmlspecialchars($instance['rss']);
?>
get_field_name('twitter') . '">' . ('Twitter:') . '
';
echo '
i.e: webdesignergeeks
';
echo '
';
echo '
i.e: webdesignergeeks
';
echo '
';
echo '
i.e: webdesignergeeks
';
}
}
function TRR_Widget() {
register_widget('TRRWidget');
}
add_action('widgets_init', 'TRR_Widget');
add_action('wp_head', 'addHeaderCode');
?>
Step 5: Adding CSS to this Plugin .php File
Now, every html element should look at perfect position with good style effect. CSS script will help you to do this.
function addHeaderCode() {
echo '
' . "n";
}
add_action('wp_head', 'addHeaderCode');
CSS Code
a.subscribeSidebarBox {
background-color: #FAFAFA;
border-radius: 10px 10px 10px 10px;
}
a.subscribeSidebarBox {
margin-top:10px;
border: medium none;
cursor: pointer;
display: block;
height: 60px;
margin-bottom: 8px;
position: relative;
font-decoration:none;
-moz-box-shadow: 0 0 5px #888;
-webkit-box-shadow: 0 0 5px#888;
box-shadow: 0 0 5px #888;
}
#subscribeRSS .icon {
background-position: 0 -50px;
}
#followTwitter .icon {
background-position: -100px -50px;
}
#subscribeEmail .icon {
background-position: -200px -50px;
}
#sidebarSubscribe .icon {
height: 45px;
left: 10px;
top: 10px;
width: 55px;
}
#sidebarSubscribe .count {
font-family: arial !important;
font-size: 20px;
font-weight: bold;
left: 70px;
text-decoration: none;
top: 23px;
}
#sidebarSubscribe .title {
font-family: arial !important;
font-size: 12px;
left: 70px;
text-decoration: none;
top: 8px;
}
#sidebarSubscribe span {
color: #6E6E6E;
display: block;
padding: 3px;
position: absolute;
text-shadow: 1px 1px 0 white;
}
.subscriberStats {
height: 35px;
padding: 5px;
width: 220px;
}
.socialIcon {
float: left;
font-size: 28px;
height: 32px;
line-height: 32px;
margin-right: 10px;
}
.subscriberCount {
border-bottom: 1px dotted #CCCCCC;
color: #999999;
float: left;
font-size: 28px;
line-height: 32px;
margin-right: 10px;
}
Conclusion

Its now time to create your own widgets !
If you’ve ever created or attempted to create a widget in WordPress, then you can probably see how much easier this is. To help people learn the new system, I’ve put together an example widget. I’ve left loads of comments about what code does what in the file, so it should be pretty easy to follow: I am enjoying working with the new widget class. I like to release a few new widgets in the near future. But, I would love to see what all you come up with. Good Luck :)

.'/wp-content/plugins/twitter-rss-social-stats/img/twitter.png)
.'/wp-content/plugins/twitter-rss-social-stats/img/rss_feed.png)
.'/wp-content/plugins/twitter-rss-social-stats/img/rss_email.png)

This is good stuff Ajay, keep it up! Hmm am going to see if we can do something similar with Facebook pages too..
Just noticed you have already done the facebook version on your blog
Also noticed that you are displaying total subscribers as 1584 which am guessing you have calculated by adding the fb, twitter and mail subscribers… What if they have common subscribers haha
Just a food for thought.
Thanks brother!
if you want to use fb stats counter may this link can help you http://www.problogdesign.com/wordpress/how-to-get-facebook-twitter-and-rss-counts-wp/
There’re 2 things we should consider while following this tutorial:
- The database: Do we actually need to create an additional table just for saving some stats? Can we use options instead? Using options have some big benefit: easier to get/set/update, and no need to write raw SQL queries.
- Cache: Every time we load the page, 3 external requests will be sent. Is it worth? Why don’t we use cache for that? Essentially, the stats don’t change for a short-time (like a day), so applying a cache mechanism (like transient) is a good way to reduce server load, and thus, page load time.
Rilwis, this is tutorial for beginner those who can learn that how to use db.
If you do not want to use db its fine.
And the second point is perfect, will improve it surely like 8 hour cache mechanism.
I have the same issues to point: Database Table and Loading external files every-time you visit the website. I, on the other hand, have implemented the same solution in a theme I’ve build, querying the Facebook fans number too, using the WordPress Transient API – it’s wonderful.
As i told in my last comment
1. if you want to use fb stats counter may this link can help you http://www.problogdesign.com/wordpress/how-to-get-facebook-twitter-and-rss-counts-wp/
2. No you do not need to re-save the widget every time.
If you do not want to request API each time you can use Transients API for like 8hr or 24hr as you like.
You misread me. I said I have developed such a solution, including the Facebook thing and I have used Transient API to save the values. I did not ask for explanations.
I am Learning to code my own WordPress Plugin and this Tutorial helps me a lot.
hey..ajay..thanks..its much helpful to me..put such articles regularly..thanks..!
Hey Man !! That’s great. Keep it up.
Congrats and it’s just great.
extensive tutorial, but now I can also show my followers in the tuts+ style …
This is a pretty extensive tutorial, but it’s worth it considering you can display the numbers of your followers in tuts+ style
Thanks:)
You can format its style by editing style.css file to display like tuts+ style.
Nice one Ajay .
I don’t see how you update the numbers. Is it once you have it, you cannot change it? It seems you have to go to Widgets page to re-save the widget to update the subscribers numbers. Am I missing something?
Good tutorial…
I do have the same question.. can’t we use options instead creating table? Anyway the plugin that you are using on your site looks quite interesting too.. i would definitely give it a try. any how great post and great explanation overall. Thanks for writing such nice post. waiting for your next!!
Great Plugin! Keep it up the good work…
Awesome! I wonder how many new premium themes will have this widget now…
Awesome! now i am going to try it right now!
Thank You For This Tutorial , it was very helpful for my blog.
pretty awesome. would be nice if there’s a way to implement google+ too
Ok, so, I’m working on this, and trying to get this to work, but I cannot get the Twitter followers count to work…
The following:
—————-
$twit = file_get_contents(‘https://twitter.com/users/show/'.$twitter.'.xml‘);
preg_match( ‘/\(\d+)\/’, $twit, $matches );
if ( $matches[1] )
$twitter_f = $matches[1] . “+ Followers “;
else
$twitter_f = “0″;
—————-
Is not working. Regardless of wether or not I code it myself, copy your source files (wich by the way, is inconsistent with the tutorial code given). The example above is the cide from your source files. While in the tutorial, the line with preg_match says:
preg_match( ‘/(d+)/’, $twit, $matches );
I like the tutorial in a whole, but I prefer source files and tutorials to actually match up, and I cannot seem to get that line to work no matter what, cause no matter what I and what I try to match it up to, it will not find the match in the XML file.
Pluss, on top of that, if I am to take your version from the wordpress.org plugin section, you put in the following:
preg_match( ‘/\(\d+)\/’, $twit, $matches );
Wich again is a different version than what you provide in the tutorial files, and also from the source files given in the tutorial above.
As I said, I appreciate the tutorial, and I’m sure I’ll find a sollution, but again, if you are to give a tutorial away, I beg you to at least give us the full source code, or a working tutorial code, if not, how are we to be able to use this to further our own development?
However, besides what I mentioned above, good tutorial, and I cannot complain on the explanation of things in the tutorial.
+ I would also like to point out that your published plugin (http://wordpress.org/extend/plugins/twitter-rss-social-stats/) is not working.
At least not on my site.
Anyone else out there have success/failure with this plugin?
I believe the RSS and Subscribe by EMAIL is working allright, but I cannot get the twitter part of the widget to actually take into the count how many followers one have.