While trying to add widgets to this blog for this post, I had to learn how to write a Wordpress widget. Up until now I had just customized the left_sidebar.php and sidebar.php files in my chosen theme directory, and it had worked fine. However, the only way to install a SezWho badge was via widgets, which caused me to use a dynamic sidebar, which replaced my very nicely built static sidebar.
So I set about making a few widgets to restore my custom sidebar content. As it turns out (and I can only vouch for Wordpress v2.3.2), this is what is needed:
1. Create a file in plugins/widgets (I had to create the widgets subdirectory), I called it my_networks.php
2. In my_networks.php, you’ll need a commented header such that Wordpress will recognize it as being a plugin. Here is an example:
/*
Plugin Name: My Networks
Plugin URI: http://site.com
Description: Network Widgets
Author: You
Version: 0.1
Author URI: http://yoursite.com
*/
3. Define a function that prints out your custom content. For example:
function widget_mynetworks($args) {
4. There are 4 special PHP variables passed to you via the $args array - before_widget, before_title, after_title, and after_widget. It would behoove you to echo as follows:
echo $args['before_widget'];
echo $args['before_title'];
echo $whatever_your_title_is;
echo $args['after_title'];
echo $your_custom_content;
echo $args['after_widget'];
5. Use the official Wordpress sidebar widget registration function to register your custom content function. I would recommend wrapping the call as follows:
function widget_mynetworks_register() {
if ( function_exists('register_sidebar_widget') )
register_sidebar_widget(__('My Networks'), 'widget_mynetworks');
}
6. Add a hook to run this registration when the main Wordpress “init” function runs, as follows:
add_action('init', 'widget_mynetworks_register');
7. Activate the plugin (It will have the name of Plugin Name from step #2).
8. Go to Presentation -> Widgets, and drag the widget called “My Networks” (or whatever you registered it as in the register_sidebar_widget call in step #5) into the sidebar of your choice.
Enjoy! I know I’m the last person on Earth to learn how to do this, but just in case I’m not, and there’s one more person, you’re welcome.













No user commented in " Wordpress widgets "
Follow-up comment rss or Leave a TrackbackLeave A Reply