Turning a WordPress Sidebar Plugin Into a Widget
Converting a WordPress plugin to a widget doesn’t have to be difficult, but because the official API’s over at wordpress.org are so lacking in detail (the example they provide won’t even work if you cut and paste), many developers can become frustrated with the process.
STEP 1: Using a widget to call a plugin function (no user input)
To begin, assume you have a very simple sidebar plugin that can be called by editing the sidebar theme directly. In your plugin file, there is some function called “nifty_stuff” that outputs some sort of html code to display in the sidebar. In the bad old days of WordPress, the only way a user could display such a plugin would be to edit their theme and add the line of code provided by the plugin author to some point in their sidebar.php file (or whatever the sidebar’s name happens to be). And in older wordpress versions and themes this is still what a blogger needs to do, so you want to leave your user with that option.
If the plugin function requires no input from the user, then the following code will add it to their widgets menu where they can simply drag and drop it into a simplified representation of their sidebar. Just add this code to the same script that holds the “nifty_stuff” function:
function widget_nifty_stuff_init() {
if(!function_exists(‘register_sidebar_widget’)) { return; }
function widget_nifty_stuff($args) {extract($args);
echo $before_widget . $before_title . $after_title;
nifty_stuff();
echo $after_widget;}
register_sidebar_widget(‘Nifty Stuff’,’widget_nifty_stuff’);}
add_action(‘plugins_loaded’, ‘widget_nifty_stuff_init’);
Going through the code, what’s happening is that we first want to create a wrapper for our widget function.
Without that wrapper, php will attempt to use the function “register_sidebar_widget” before the script containing it has been loaded. Using the ‘plugins_loaded’ action hook to run the init function ensures that everything loads in the right order first.
The lines surrounding the call to nifty_stuff are there because the widget-enabled wordpress themes may use them, and so they must be supported.
The register_sidebar_widget function associates a label for the widget with the actual widget function that will get called if the user adds it to their sidebar. That label is what the user sees in their widgets menu.
Now, that’s all well and good for really simple plugins. But if your widget needs that user input, then keep reading to learn how to add a widget control. continue reading »
September 30 2007 | open-source and technical articles | 4 Comments »