Creating WordPress Widget Plugin

Plugins add features to your WordPress website. Several plugins are available to download onlineThese plugins You can create plugins for WordPress to add new WordPress can extend its full feature by adding extra help thru widgets. In this tutorial, we will tackle widget creation within a small plugin. Okay, so let’s get started.

Step 1, create a plugin. This is not the hardest part though, a plugin is an extra code added to WordPress once you activate it. Before creating plugin, make sure that you have a code editor and FTP or CPanel access – you can download any code editor you prefer. 

Login to your CPanel and go to: File Manager > public_html/wp-content/plugins, you will see all the installed plugins in your site here.

Open your preferred text editor. Create widget-plugin-test.php then input the following codes.

<?php
/*
Plugin Name: Hello Widget Plugin
Plugin URI: https://www.adaptsites.com/widget-plugin/
Description: This plugin adds a custom widget.
Version: 1.0
Author: John Cook
Author URI: https://www.adaptsites.com/widget-plugin/
License: GPL2
*/

Save it. Now create a folder named widget-plugin, put the newly created php file into the folder. Upload the folder in your wp-content/plugins folder in your CPanel.

Voila! you successfully created a simple plugin. To make sure that you successfully created the plugin, go to your administration area > plugins. If your plugin appears in the plugins list you’re good, otherwise make sure you followed my instructions and try again. You can now activate the plugin.

2. Widget

Now the second step is to create widget.This widget will be a PHP class extending the core WordPress class WP_Widget.

class Widget_Plugin extends WP_Widget {

	// Main constructor
	public function __construct() {
		/* ... */
	}

	// The widget form (for the backend )
	public function form( $instance ) {	
		/* ... */
	}

	// Update widget settings
	public function update( $new_instance, $old_instance ) {
		/* ... */
	}

	// Display the widget
	public function widget( $args, $instance ) {
		/* ... */
	}

}

// Register the widget
function register_widget_plugin() {
	register_widget( 'Widget_Plugin' );
} add_action( 'widgets_init', 'register_widget_plugin
' );

The following functions gives WordPress all the information the system needs to be able to use the widget, please see the explanation below:

  • Constructor – to initiate the widget
  • Form – to create the widget form in the administration
  • Update – to save widget data during edit process
  • Widget – to display the widget content on the front-end

Let’s edit those functions one by one and fill in all the important code for our widget.

Constructor

The constructor is the part of code that defines the widget name and main arguments. See the codes below and update your class above.

// Main constructor
public function __construct() {
	parent::__construct(
		'widget_plugin',
__( 'Widget Plugin', 'text_domain' ), array( 'customize_selective_refresh' => true, ) ); }

Form

 The form function creates the widget form settings in the WordPress administration area. This is where you’ll input the data to be displayed on your site. Make sure you update your form class above.

// The widget form (for the backend )
public function form( $instance ) {

	// Set widget defaults
	$defaults = array(
		'title'    => '',
	);
	
	// Parse current settings with defaults
	extract( wp_parse_args( ( array ) $instance, $defaults ) ); ?>

	<?php // Widget Title ?>
	<p>
		<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( 'Widget Title', 'text_domain' ); ?></label>
		<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
	</p>

<?php }

This function created an input type text where you can enter widget title. Notice esc_attr() when adding form field? This is necessary for security reasons. Whenever you output a user-defined variable on your site, you should make sure that it’s sanitized.

Update

This function is assign for editing widget information. The update function is really simple, just add the following codes:

// Update widget settings
public function update( $new_instance, $old_instance ) {
	$instance = $old_instance;
	$instance['title']    = isset( $new_instance['title'] ) ? wp_strip_all_tags( $new_instance['title'] ) : '';
	return $instance;
}

Based on the code above, the update function check for each setting and if it’s not empty save it into the database. We used wp_strip_all_tags() and wp_kses_post() functions – these are used to sanitize the data before added to the database. 

Widget

And lastly, widget function. This will output the content on your website and its what your visitor see.  This function can be customized to include CSS classes, and specific tags to match perfectly your theme display.

// Display the widget
public function widget( $args, $instance ) {

	extract( $args );

	// Check the widget options
	$title    = isset( $instance['title'] ) ? apply_filters( 'widget_title', $instance['title'] ) : '';

	// WordPress core before_widget hook (always include )
	echo $before_widget;

        // Display the widget
        echo '<div class="widget-text wp_widget_plugin_box">';

		// Display widget title if defined
		if ( $title ) {
			echo $before_title . $title . $after_title;
		}

	echo '</div>';

	// WordPress core after_widget hook (always include )
	echo $after_widget;

}

Go back to your WordPress administration area and navigate to Plugins > Installed Plugins > Activate Hello Widget Plugin

Now go to Appearance > Widgets, find the My Custom Widget > Add Widget and in the image below you can see the widget with the title input type text we created a while ago > click Done > Save

Simple right? If you want, you can download the full code here and upload it in your plugin folder using your FTP or CPanel.

Log In To Your Account