WordPress: Create a Custom Widget (Part 3)

| 0 comments

This entry is part of my WordPress development series, providing tutorials on specific things you can do in WordPress. Read some more?

In Part 3 of creating a custom widget, we are updating the code from Part 2 so that it utilizes four arguments from register_sidebar(). The only changes we need to make are to the front-end display.

Update the Front-End Display

<?php
// Front-End Display of the Widget
public function widget( $args, $instance ) {
	// Saved widget options
	$title = apply_filters( 'widget_title', $instance['title'] );
	$catName = $instance['cat_name'];
	$catAge  = $instance['cat_age'];
	$favToy  = $instance['fav_toy'];
	$desc    = apply_filters( 'widget_textarea', empty( $instance['description'] ) ? '' : $instance['description'], $instance );

	// Display information
	echo $args['before_widget'];
		if ( !empty( $title ) ) {
			echo $args['before_title'] . $title . $args['after_title'];
		}
		if ( !empty( $catName ) ) {
			echo '<p><strong>Name:</strong> ' . $catName . '<br />';
		}
		if ( !empty( $catAge ) ) {
			echo '<strong>Age:</strong> ' . $catAge . '<br />';
		}
		if ( !empty( $favToy ) ) {
			echo '<strong>Favourite Toy:</strong> ' . $favToy . '</p>';
		}
		if ( !empty( $desc ) ) {
			echo wpautop( $desc );
		}
	echo $args['after_widget'];
}
?>

First we add the variable $args to our function on line 3. This is an array that stores the widget arguments passed from register_sidebar().

On line 12, we remove our opening <div> and replace it with $args['before_widget'] which passes the value of the widget argument 'before_widget' from register_sidebar(). On line 28, we close it with $args['after_widget'], which passes the value of the widget argument 'after_widget'.

On line 14, we use $args['before_title'] and $args['after_title'] instead of <h3> and </h3>. These pass the values of the widget arguments 'before_title' and 'after_title' from register_sidebar().

And that is it! This is a very simple update, and your custom widget will now use the same HTML structure as other widgets. The default values of these arguments are a list item and H2, however you can change these to other HTML tags when registering your sidebars.