Making a Basic Plugin and Widget to Display Followers, Fans and Subscribers

I’ve never made a plugin before. I really never thought I had a need. But recently I changed my way of thinking. So I decided to learn how to make a plugin to display my followers, fans and subscribers in a widget. Now this widget is about as basic as possible. But it’s a starting point. I learned something, and maybe you can too! Let’s take a look at the why and how.

After reading several articles about making functionality plugins for your install I started thinking. You see functionality plugins are pretty important. If you register a custom post type, or a taxonomy, or maybe some meta boxes, those are not theme specific. Down the road if you ever change themes, you will still want this functionality. So I decided to go through all my functions, and I have a lot. I sorted them out into theme specific and site specific.

That can be a hard distinction to make. The examples I gave above are simple. You’ll want your CPTs and meta boxes no matter what theme you are using. I have other functions though, like my related posts function. The actual function of calling the related posts is site specific. But then I use another function to add the links to the bottom of the twentyten theme. That is theme specific, since the function will be different for the twenty eleven theme.

Anyway, there’s a generic look into my thought process. I went through and picked out every function I would like regardless of theme, which is not specifically tied into a certain theme somehow. I did this for all of my sites, and made my functions into plugins. It honestly took about an hour, to do all my sites. It’s not hard, let’s take a look!

The first thing I did was make a new folder inside my wp-content->plugins folder. I just named it voodoopress_plugin. Inside that I made a new file named plugin.php. And on top of that I added this header:

<?php
/*
Plugin Name: VoodooPress Functions
Plugin URI: http://voodoopress.com
Description: Non-theme specific functions for VoodooPress.
Author: Rev.Voodoo
Author URI: http://www.rvoodoo.com
Version: 1
License: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/

And that’s it! Seriously. It’s a plugin. Now obviously it won’t do anything. There’s no code! So let’s get started on that. Here’s some words of wisdom for your workflow. I got myself out of order yesterday and crashed my site. First make a backup copy of your functions’php file in case you screw anything up. The best thing you could do is work offline. Take the code from your functions.php, put it into your plugin. When you are done, save the new functions.php without the functions, and then activate the plugin.

If you are impatient like me and do all of your work online on a live site, remember this. Cut the code out of functions.php and paste it into the plugin. Then save functions.php first. Then save the plugin. The basic idea here is that you cannot have the same bit of code active in functions.php and an activated plugin. That will crash your site. Work however it makes sense to you, just avoid running the same code in 2 places.

So it’s really as simple as just plopping all your functions into the plugin. Everything will work as though it’s in functions.php. Here’s another important thing I learned. What if you reference images in your functions? We’ll look at my favicon hook for instance. A while back we looked at this hook:

//ADDS FAVICON TO HEADER
function childtheme_favicon() { ?>
    <link rel="shortcut icon" href="<?php echo bloginfo('stylesheet_directory') ?>/images/favicon.ico" type="image/x-icon" />
    <link rel="icon" href="<?php echo bloginfo('stylesheet_directory') ?>/images/favicon.ico" type="image/x-icon" />
<?php }
add_action('wp_head', 'childtheme_favicon');

That pulls the favicon from the images folder in your theme for use. Well, if you move this code to a plugin, it will still work. But it’s not so portable. I want my favicon to move around with this plugin. Everything should be in one place so that it is truly portable. So let’s update the code. First, copy your favicon from your theme’s images folder and put it into the plugins folder. And now the above code becomes:

//ADDS FAVICON TO HEADER
function childtheme_favicon() {
	<link rel="shortcut icon" href="<?php echo get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)).'/favicon.ico'; ?>" type="image/x-icon" />
	<link rel="icon" href="<?php echo get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)).'/favicon.ico'; ?>" type="image/x-icon" />
<?php }
add_action('wp_head', 'childtheme_favicon');

You can see the change in the path there. That pulls the images from your plugin instead of the theme. So for any functions you have that reference images, I would recommend you copy the images to the plugin and update the path to point to the plugin. True portability!

OK, now onto the widget. I had set up some code to grab my total number of RSS subscribers, Facebook fans, and Twitter followers. The code I grabbed is from this tutorial. I decided I wanted my counts to be theme independent, so I dropped this code into my new plugin.

// GRAB UP OUR SUBSCRIBER TOTALS
/**
 * Retrieve transient value.
 *
 * Returns a transient value, or updates that transient if it has expired.
 *
 * @param $name String. Name of the service, e.g. twitter
 * @return String. New transient value.
 */
function pbd_get_transient($name = 'twitter') {
	$transName = "pbd-transient-$name"; // Name of value in database.
	$cacheTime = 8; // Time in hours between updates.

	// Do we already have saved tweet data? If not, lets get it.
	if(false === ($trans = get_transient($transName) ) ) :

		// Make the name of the function that gets our transient value.
		$func = "pbd_get_$name";
		if(function_exists($func) ) {
			$trans = $func();
		} else {
			$trans = 'Function not found.';
		}

		// Did we get a positive number? If not, use the old value.
		if(!absint($trans) > 0)
			$trans = get_transient($transName . '-old');

		// Save our new transient, plus save it in the longer "backup" transient.
		set_transient($transName, $trans, 60 * 60 * $cacheTime);
		set_transient($transName.'-old', $trans, 3 * 60 * 60 * $cacheTime);
	endif;

	return $trans;
}

/**
 * Get Facebook Page Fan Count.
 */
function pbd_get_facebook() {
	$json = wp_remote_get("http://graph.facebook.com/VoodooPress/198647740164688");

	if(is_wp_error($json))
		return false;

	$fbData = json_decode($json['body'], true);

	return intval($fbData['likes']);
}

/**
 * Get Twitter follower count.
 *
 * @return Int. Twitter follower number.
 */
function pbd_get_twitter() {

	$json = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name=wpvoodoopress");

	if(is_wp_error($json))
		return false;

	$twitterData = json_decode($json['body'], true);

	return intval($twitterData['followers_count']);
}

/**
 * Get RSS subscriber count from FeedBurner.
 *
 * @return Int. RSS follower number.
 */
function pbd_get_rss() {
	$xml = wp_remote_get('http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=voodoopress');

	if(is_wp_error($xml))
		return false;

	$sxe = new SimpleXMLElement($xml['body']);

	return intval($sxe->feed->entry['circulation']);
}

I’m not going to explain the above, as I got it from the linked post above at Pro Blog Design. It’s simple enough to copy it and switch out your account names. So when I had that in my functions.php, I had Otto’s php code widget for my sidebar, in which I used this:

	<div class="iconBox">
		<a href="http://voodoopress.com/feed/">
			<img src="<?php echo get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)).'/icons/rss70.png'; ?>" alt="Subscribe to Our RSS Feed" />
		</a>
		<br />
		<span>
			<?php echo number_format(pbd_get_transient('rss') ); ?>
			<br />
			Subscribers
		</span>
	</div>
	<div class="iconBox">
		<a href="http://www.facebook.com/?ref=home#!/pages/VoodooPress/198647740164688">
			<img src="<?php echo get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)).'/icons/facebook70.png'; ?>" alt="Visit Us on Facebook" />
		</a>
		<br />
		<span>
			<?php echo number_format(pbd_get_transient('facebook') ); ?>
			<br />
			Fans
		</span>
	</div>
	<div class="iconBox">
		<a href="http://twitter.com/wpVoodooPress">
			<img src="<?php echo get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)).'/icons/twitter70.png'; ?>" alt="Follow us on Twitter!" />
		</a>
		<br />
		<span>
			<?php echo number_format(pbd_get_transient('twitter') ); ?>
			<br />
			Followers
		</span>
	</div>
	<div class="clear"></div>

inside of the widget to display my followers. After setting up the plugin, I realized I would have to remember to copy that code from the old php widget to the new php widget. Seemed like something I’d forget. So in the spirit of keeping things together I turned that block of code into a widget by putting code into my plugin as follows:

// BUILD OUR WIDGET TO SHOW OUR FOLLOWERS
function voodoo_followers() { ?>
	<div class="iconBox">
		<a href="http://voodoopress.com/feed/">
			<img src="<?php echo get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)).'/icons/rss70.png'; ?>" alt="Subscribe to Our RSS Feed" />
		</a>
		<br />
		<span>
			<?php echo number_format(pbd_get_transient('rss') ); ?>
			<br />
			Subscribers
		</span>
	</div>
	<div class="iconBox">
		<a href="http://www.facebook.com/?ref=home#!/pages/VoodooPress/198647740164688">
			<img src="<?php echo get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)).'/icons/facebook70.png'; ?>" alt="Visit Us on Facebook" />
		</a>
		<br />
		<span>
			<?php echo number_format(pbd_get_transient('facebook') ); ?>
			<br />
			Fans
		</span>
	</div>
	<div class="iconBox">
		<a href="http://twitter.com/wpVoodooPress">
			<img src="<?php echo get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)).'/icons/twitter70.png'; ?>" alt="Follow us on Twitter!" />
		</a>
		<br />
		<span>
			<?php echo number_format(pbd_get_transient('twitter') ); ?>
			<br />
			Followers
		</span>
	</div>
	<div class="clear"></div>
<?php }

function widget_voodoo_followers($args) {
	extract($args);
	echo $before_widget;
	echo $before_title;?>TITLE HERE<?php echo $after_title;
	//CONTENT GOES HERE
	voodoo_followers();
	echo $after_widget;
}

function voodoo_followers_init() {
	register_sidebar_widget(__('Voodoo Followers'), 'widget_voodoo_followers');
}
add_action("plugins_loaded", "voodoo_followers_init");

You can see we really just took the code we had, and put it into the function voodoo_followers. Next we made the functionwidget_voodoo_followers. It’s pretty straight forward. You can see the usage of before_widget, before_title, after_title, and after_widget. Those call to the code in functions.php where sidebars are registered. You want to make sure you follow that format so that your new widget fits in with the theme perfectly. After we set up the widget we have to register it, you’ll see we just give it the display name of Voodoo Followers, and then call to widget_voodoo_followers which we had just set up. And at the end we latch our registered widget onto plugins loaded.

And that’s it, we are done. Now, this is a totally simple widget. Nothing is changeable by the end user. It just displays what we want it to display. In the future I will modify the plugin a bit. Starting with the ability to change up the displayed title, and the ‘titles’ of each icon…followers, subscribers, fans. Notice in the html for display, the icons are reference using the path we looked at above. Except they are in a folder called icons within the plugin. If you are trying to set up this widget, feel free to right click on each icon I have in my sidebar to use yourself. They are from a free set I downloaded. The only thing you may need to do is tweak some css. I’ve wrapped everything in divs and spans as appropriate so that part should be easy. I didn’t want to include css with the plugin, as that part will change for each theme. I want my plugin totally independent of the theme.

6 Replies to “Making a Basic Plugin and Widget to Display Followers, Fans and Subscribers”

    1. I know right? It was so easy to get started down this road. I really wish I had some more time to play around more. This was a lot of fun to figure out, and I’m looking forward to doing so much more with plugins, and widgets.

    1. Sure! Hopefully the article was a bit helpful. I used to hard code things into my sidebar, but as soon as I get time, I’m making all my stuff into widgets. Far cooler, and portable between sites

Leave a Reply