Advertisement
Plugins

Create a TwitterRSS Stats Widget for WordPress

by

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

Files

The Plugin Basics

The heart of a WordPress plugins is the below 2 functions (commonly called `hooks`):

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.
Add-Plugin


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']);
		?>
		

'; 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']);	
		?>
			

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

Files

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  :)

Related Posts
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Custom Database QueriesApplication foundation 400
    Throughout this series, we've been looking at the various facilities that make it possible to treat WordPress as a foundation for web application development. Thus far, we've covered a lot of ground: We've talked about how WordPress is more of a foundation rather than a framework. We've discussed the nature of the the Event-Driven Design Pattern. There's been a discussion of Email, User Management, Saving Data, Retrieving Data ...and more. In the most recent articles, we've been talking a look at how to handle queries against the WordPress database through the use of WP_Query and WP_User_Query.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: The Footer FileCreating wordpress theme from html 400
    In this series, you've been learning how to create a WordPress theme form static HTML. Up to this point, you have: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu added widget areas to the header and sidebar. Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML - Adding WidgetsCreating wordpress theme from html 400
    In this series, you've learned how to convert a static HTML file to a WordPress theme and edit the header file. So far you've: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu. Read More…
  • Code
    Plugins
    A Better Forum List Widget for bbPressBbpress
    When bbPress was still a standalone installation, I had tried it out and wasn't really impressed. Things were clunky and it didn't always work the way it was supposed to. After languishing for a few years, Automattic decided to take bbpress and turn it into a plugin, improving the functionality leaps and bounds and making it a strong contender amongst other forum option for WordPress.Read More…
  • Code
    Business
    Making the Best of Google AdSense in WordPressGoogleadsensepreview
    Blog monetization is not a "must", but it's a very important source of motivation. Whether you're blogging alone or along with some authors you gathered, earning even a few bucks a month can change your and/or your authors' approach to your blog. Since Google AdSense is one of the easiest and most popular ways for blog monetization, we're going to see how to use it with a WordPress blog with multiple authors. (Although, this tutorial will also work for single bloggers.) We'll be covering how to set up profile fields for authors' AdSense ads and how to display those ads with a function, with a widget, with a shortcode and automatically inside posts.Read More…
  • Code
    Widgets
    Twitter Trends Widget for WordPressPreview
    In this tutorial we are going to create a WordPress widget that displays Twitter Trends by region. We will use Twitter's Trends API and update trends after a specific time duration using WordPress' Transients API.Read More…