TextMate WordPress Widget Snippet

I love WordPress’ sidebar widgets. I also despise coding them.

I love how they let me offload menial management tasks directly to clients, avoiding all the “Change this word to another word!” e-mails. But every time I code them, it seems to involve 15 minutes of Googling, copy-pasting from a previous widget, and looking at documentation.

So I created this TextMate “snippet” to make it easier:

class ${1:PREFIX_Name}_Widget extends WP_Widget {
	function $1_Widget() {
		\$widget_ops = array( 'classname' => '${2:CSS class name}', 'description' => '${3:Description}' );
		\$this->WP_Widget( '$2', '${4:Title}', \$widget_ops );
	}

	function widget( \$args, \$instance ) {
		extract( \$args, EXTR_SKIP );
		echo \$before_widget;
		echo \$before_title;
		echo '$4'; // Can set this with a widget option, or omit altogether
		echo \$after_title;

		//
		// Widget display logic goes here
		//

		echo \$after_widget;
	}

	function update( \$new_instance, \$old_instance ) {
		// update logic goes here
		\$updated_instance = \$new_instance;
		return \$updated_instance;
	}

	function form( \$instance ) {
		\$instance = wp_parse_args( (array) \$instance, array( ${5:array of option_name => value pairs} ) );

		// display field names here using:
		// \$this->get_field_id('option_name') - the CSS ID
		// \$this->get_field_name('option_name') - the HTML name
		// \$instance['option_name'] - the option value
	}
}

add_action( 'widgets_init', create_function( '', "register_widget('$1_Widget');" ) );

Just create a WordPress TextMate bundle, create a new snippet, paste in that code and give it a trigger like wpwidget. Then just type that trigger, press TAB, and you’ll be in the first field. Type, hit TAB to go to the next field. Places where you enter the same thing twice are handled—you only have to enter it once. There are some helpful comments that’ll guide you through the rest once you’ve filled out the basics. I find that with this snippet, I can code up a new widget in a couple of minutes, tops. This is definitely going to make it more likely for me to create a widget for a client instead of just cheating and editing their theme by hand myself.