Wordpress

How to create a widget plugin in WordPress

How to create a widget plugin in WordPress

Today we will see, how we can create custom widgets in WordPress. Widgets are the essential part of WordPress frontend to display content. We going build it in the form a plugin because by doing so we are preserving widget from getting deactivate in case there is a change in theme.

Introduction

A widget is a self-contained block which can be used to show any type of content in the WordPress frontend. We must place widgets on the sidebar in order to show them on the frontend of the site.

It is good practice to build widget inside a plugin instead of a theme. That way if the theme is changed, it will not affect the functionality of a widget on the frontend.

In this tutorial, we will be building a widget which will show an embedded video from using video URL from YouTube. In the dashboard, the user will put our widget to sidebar & will provide URL of his YouTube video.  Then we will show that video on the sidebar in the frontend.

So let's begin! First, we will build a plugin.

Building a WordPress plugin

A Plugin is like an extension, which can be used to extend WordPress functionality. It is really easy to build a plugin in WordPress. We will start our tutorial by creating a plugin for our widget.

To create a plugin we just need a folder "youtube-widget" inside the directory "/wp-content/plugins/".

new-plugin-location

After creating "youtube-widget" directory, its time register our plugin. To register our plugin in WordPress dashboard we need need to create a file called "youtube-widget.php" file inside our plugin directory. And add following code into that file.

<?php

/**

* Plugin Name: YouTube Widget

* Plugin URI: https://github.com/camelthemes/youtube-widget

* Description: A plugin to show YouTube video using widget.

* Version: 0.1

* Author: CamelThemes

* Author URI: https://camelthemes.com

*/

After adding this code this its time to check if our plugin being shown in WordPress dashboard. To check that, open WordPress dashboard & visit "Plugins" section from the sidebar. You should see our plugin there like this:

new-plugin-in-dashboard

That's it! we have successfully created our plugin. If you don't see the plugin just we made in the dashboard, then recheck the code & try again. After that, go ahead & click on "Activate" button to activate the plugin. You should see a successful plugin activation message.

Now that we have created a plugin for our widget, Its actual time to begin the development of our YouTube widget.

Building a WordPress widget

To build WordPress widget, we will need to extend WP_Widget class to our YouTube_Widget class. WP_Widget class is located in "/wp-includes/class-wp-widget.php".  There are four methods which we will need to modify in our extended class to build our widget.

Here little overview of what our YouTube_Widget class will look like:

class YouTube_Widget extends WP_Widget {

public function __construct() {

// here we will define widget information

}

public function widget( $args, $instance ) {

// this will output the contents of widget in frontend

}

public function form( $instance ) {

// this will show option/form in admin dashboard

}

public function update( $new_instance, $old_instance ) {

// here method will process/update the widget data

}

}

The "_construct" method is used for registering widget in the admin panel. It will contain information about widget such as "name" & "description". The "widget" method will show the contents of the widget in the frontend. To show the widget in the frontend, we must add our widget to a widget area/sidebar.

Next, "form" method is used for like its name suggests, creating a form in admin panel to get input values from the user. At last, "update" method handles the widget data. Like when a user saves the widget form, the input values provided by a user are processed by this method.

Now that we are familiar with WP_Widget class we are going to start building our widget.

Registering widget in the admin panel

To register our widget in admin panel we will need to add following code in "youtube-widget.php" file. This code has "_construct" method which has the information about our widget. So ahead & add following code in "youtube-widget.php".

class YouTube_Widget extends WP_Widget {

/**

* Widget information

*/

public function __construct() {

parent::__construct(

'youtube_widget', // Widget ID

'YouTube Widget', // Widget Name

array( 'description' => 'YouTube widget for displaying video in sidebar.' ) // Widget description

);

}

}

// Hook to register widget in dashboard

add_action( 'widgets_init', function() {

register_widget( 'YouTube_Widget' );

});

After adding about code goto dashboard & visit "Plugins" section. You should see our widget there.

new-widget-registration

If you are not seeing the newly created widget in Widgets section. Then make sure you have inserted correct code in "youtube-widget.php" & also check that our plugin is activated from plugins section.

Creating a form for the widget

Now that we have a widget in the dashboard, we will create a form to accept video URL from the user.  So go ahead add following "form" method in our YouTube_Widget class in "youtube-widget.php" file.

/**

* Create a form in admin panel

* @param array $instance // Previously saved values from database

*/

public function form($instance) {

$url = isset( $instance[ 'url' ] ) ? $instance[ 'url' ] : ''; ?> // If has previous saved URL in database.

<p>

<label for="<?php echo $this->get_field_name( 'url' ); ?>"><?php _e( 'YouTube Video URL:' ); ?></label>

<input class="widefat" id="<?php echo $this->get_field_id( 'url' ); ?>" name="<?php echo $this->get_field_name( 'url' ); ?>" type="text" value="<?php echo esc_attr( $url ); ?>" />

</p>

<?php

}

After adding above code ("form" method) to YouTube_Widget class, try adding our widget to the sidebar. You see a form asking for YouTube video URL like this:

widget-on-sidebar

Hurray! we have successfully created a form for our widget. But if you try to add some value in the form it will not save. That is because we don't have that ability for our widget yet. We should give our widget ability to save/update data in the database.

Saving/Updating widget data

Now, we will build update method for YouTube_Widget class. Update method will take new data from form & will update previous values. Add following code for update method in "youtube-widget.php" inside YouTube_Widget class after form method.

/**

* Update widget options

*

* @param array $new_instance // New values from form

* @param array $old_instance // Previous values from database

* @return array $instance

*/

public function update($new_instance, $old_instance) {

$instance = array();

$instance['url'] = ( ! empty( $new_instance['url'] ) ) ? strip_tags( $new_instance['url'] ) : '';

return $instance;

}

This method will take new values from form & will pass on to WordPress to save them in the database. Now you should be able to save/update values in our Widget. Congrats!!!

So our widget is basically ready in dashboard section. But we are forgetting one thing here, it still not going to show up on the frontend. That is because we haven't told WordPress that how our widget is going to render on the frontend.

To do that, we will need to create a method called "widget" in our YouTube_Widget class, which will take these values from the database. And will use that values to show our expected YouTube video on the frontend.

Rendering widget output

Next, add "widget" method in our class with following code which outputs the content for the widget in the frontend. Here we are also converting normal YouTube videos URL to embed URL.

/**

* Output the contents of widget

*

* @param array $args

* @param array $instance

*/

public function widget($args, $instance) {

echo $args['before_widget'];

if ($instance['url']) {

// Replace normal YouTube URL with embed URL

$url = str_replace('https://www.youtube.com/watch?v=', 'https://www.youtube.com/embed/', $instance['url']); ?>

<iframe width="100%" src="<?php echo $url; ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

<?php

}

echo $args['after_widget'];

}

Now copy the URL of YouTube video which you want to show on site. Go to widgets sections on the dashboard. Select and add our YouTube Widget to sidebar & paste the URL you copied from the video. Save that form & visit the site. You should see our video ready to be played there. Hurray!!!

That's it! We have successfully created our YouTube widget plugin. Was it fun developing a widget & a plugin right?

Your final "youtube-widget.php" should look like this.

<?php

/**

* Plugin Name: YouTube Widget

* Plugin URI: https://github.com/camelthemes/youtube-widget

* Description: A plugin to show YouTube video using widget.

* Version: 0.1

* Author: CamelThemes

* Author URI: https://camelthemes.com *

*/

class YouTube_Widget extends WP_Widget {

/**

* Widget registration

*/

public function __construct() {

parent::__construct(

'youtube_widget', // Widget ID

'YouTube Widget', // Widget Name

array( 'description' => 'YouTube widget for displaying video in sidebar.' ) // Widget description

);

}

/**

* Output the contents of widget

*

* @param array $args

* @param array $instance

*/

public function widget($args, $instance) {

echo $args['before_widget'];

if ($instance['url']) {

// Replace normal YouTube URL with embed URL

$url = str_replace('https://www.youtube.com/watch?v=', 'https://www.youtube.com/embed/', $instance['url']); ?>

<iframe width="100%" src="<?php echo $url; ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

<?php }

echo $args['after_widget'];

}

/**

* Create a form in admin panel

* @param array $instance // Previously saved values from database

*/

public function form($instance) {

$url = isset( $instance[ 'url' ] ) ? $instance[ 'url' ] : ''; ?>

<p>

<label for="<?php echo $this->get_field_name( 'url' ); ?>"><?php _e( 'YouTube Video URL:' ); ?></label>

<input class="widefat" id="<?php echo $this->get_field_id( 'url' ); ?>" name="<?php echo $this->get_field_name( 'url' ); ?>" type="text" value="<?php echo esc_attr( $url ); ?>" />

</p>

<?php

}

/**

* Update widget options

*

* @param array $new_instance // New values from form

* @param array $old_instance // Previous values from database

* @return array $instance

*/

public function update($new_instance, $old_instance) {

$instance = array();

$instance['url'] = ( ! empty( $new_instance['url'] ) ) ? strip_tags( $new_instance['url'] ) : '';

return $instance;

}

}

add_action( 'widgets_init', function() {

register_widget( 'YouTube_Widget' );

});

I have also created a GitHub repository for this plugin. You can go ahead & check that out if you are having problems creating our widget.

GitHub Repository: https://github.com/camelthemes/youtube-widget

Conclusion

In this tutorial, we build a widget to show a YouTube video on frontend by creating a quick plugin. As you see, it is easy to build widgets in WordPress. Now you should be able to build widgets in WordPress confidently.

If you have questions, feel free to ask to ask them in the comment section below. Also, follow us on Twitter @camelthemes, we are posting daily WordPress development tips, which can be helpful to improve your workflow!

Swapnil Bhavsar

Swapnil Bhavsar is PHP developer & also the founder of Camel Themes. He also blogs about Laravel & Vue.js at swapnil.co. Follow him on Twitter @swapnil_bhavsar

Comments