How I Create Widgets for WordPress

I haven’t been able to find clear instructions on how to add widgets to WordPress. This widget tutorial for developers was as close as I could get, but it applies to the Widget Plugin before WordPress included Widgets in v 2.2.

I’ve figured out a system that has worked for me. I can’t say that it is the best or only way. It’s just a way for me to accomplish what I want. That’s also why I’m not calling this a how-to.

First, create a new file called widgets.inc.php and place it in the themes folder. Here is an example based on a widget to spread Firefox:

<?php
/* Widgets I added */
	function wp_widget_firefox($args) {
	extract($args);
?>
	<?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {?>
		<?php echo $before_widget; ?>
		<?php echo $before_title; ?>
		<?php _e('Try Firefox'); ?>
		<?php echo $after_title; ?>
		<ul><li>
			<a href="http://www.spreadfirefox.com/?q=affiliates&id=YOUR_ID&t=210"><img border="0" alt="Firefox 2" title="Firefox 2" src="http://sfx-images.mozilla.org/affiliates/Buttons/firefox2/firefox-spread-btn-1b.png"/></a>
		</li></ul>

		<?php echo $after_widget; ?>
		<?php
		}
		?>
<?php
	} //close function
?>

Now edit /wp-includes/widgets.php.

FIND:

add_action('init', 'wp_widgets_init', 1);

BEFORE it, ADD:

$themes_path = '/home/ABSOLUTE/PATH/TO/BLOG/wp-content/themes';
include("$themes_path" . '/widgets.inc.php');

Edit the path accordingly.

In the wp_widgets_init() function, add these lines for each widget you want to add. Using the Firefox widget example:

$class['classname'] = 'widget_firefox';
wp_register_sidebar_widget('firefox', __('Spread Firefox'), 'wp_widget_firefox', $class);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>