Home Articles Making a widget for the Popularity Contest plugin

Making a widget for the Popularity Contest plugin


If you’re a fan of the Popularity Contest plugin like myself and are using a widgetized theme, then you must have noticed that the plugin doesn’t come with widgets that you can easily add to your sidebar. Well… today we’re going to make one.

What we’re going to do is take the basic code for a widget and just put the main Popularity Contest function inside. Sound easy, doesn’t it. Let’s go.

The basics

First of all, you need to be running at least WordPress 2.3 and if you haven’t installed the plugin yet, go to Alex King’s site and download your copy. Then upload it and activate it.

If you’re running WordPress 2.5 then you might need to make some changes as I noted here.

The widget

A widget is nothing more than just a piece of php code. It can be placed inside a plugin file, or inside the functions.php file of your theme. For this tutorial we’re going to put it inside the functions.php file.

This is the basic widget code:

function widget_popular_contest($args) {
    extract($args); ?>



Popular Articles

<?php }

The important part being the popular constest plugin function, which will print our ten most popular posts of all time:

Then we need to hook the function, so WordPress knows it is a widget:

register_sidebar_widget('Popular Articles', 'widget_popular_contest');

This might be enough, but we want to make sure the popularity contest plugin is installed, otherwise we risk to get a nasty WordPress error if we decided to deactivate the plugin. So let’s wrap our latest bit of code around the following conditional statement:


What this does is checking if the akpc_most_popular() function exists, which would mean that the plugin is there and it has been activated.

Wrapping up

That’s it, we’re all set but just to make sure here is the complete code:

function widget_popular_contest($args) {
    extract($args); ?>



Popular Articles

<?php } if(function_exists('akpc_most_popular')){ register_sidebar_widget('Popular Articles', 'widget_popular_contest'); }

The End!

Now you can go to your widgets page and add the widget to your sidebar.


Comments are closed.