Tutorial How to Create Widgets in WordPress

In WordPress, of course, there are many widgets created by developers. For those who are old in wordpress, making a widget is not difficult, but maybe many beginners are wondering how to make a widget in wordpress??

Well, here I will explain how to create a wordpress widget itself. For practice, we will create this widget in a plugin. Okay, for starters please create a new file in wp-content/plugin with the name widget_gue.php. Then fill it with this code:

/*
Plugin Name: My Widget
Plugin URI: http://www.domain.com
Description: A simple widget
Author: Nur Rohmat
Version: 1
Author URI: http://www.domain.com
*/
Next.. There are 3 main functions of a widget, namely:

function form()
update() function
widget() function
Basic Framework
The basic framework of a wordpress widget is actually very simple. Take a look at the code below:

class widget_gue extends WP_Widget{ //Example widget class
function widget_gue(){} //Widget settings (name, description, etc.)
function form(){} //form in admin page
function update(){} //function when widget is updated/saved
function widget(){} //view of a widget
}
add_action(‘widgets_init’, create_function(”, ‘return register_widget(“widget_gue”);’)); // function to load widget_gue
Step 1
We will wrap this widget in a class. The name of this class is very important. The class name and function name must be the same.

class widget_gue extends WP_Widget{}
Next we will give the identity of the widget. For example we will give the name .

function widget_gue(){
parent::WP_Widget(false, $name=__(‘GUE Widget’,’wp_widget’));
}
Step 2 function form()
The next stage we will create a form on the admin page. For example we will add a text input (for the widget title) and a textarea (for the widget content).

function form($instance){
if ($instance){
$text=esc_attr($instance[‘text’]);
$content=esc_attr($instance[‘content’]);
}
else{
$text=”;
$content=”;
}
?>

get_field_id(‘text’); ?> value=”” />

<?php echo $ content;?>
<?php
}
Step 3 function update()
The update function is used to store data entered by the user into the form. The syntax is quite simple

function update($new_instance,$old_instance){
$instance=$old_instance;
$instance[‘text’]=strip_tags($new_instance[‘text’]);
$instance[‘content’]=strip_tags($new_instance[‘content’]);
return $instance;
}
Step 4 function widget()
The next step we will set the appearance of the widget that we created. We will display the title and other user-editable parameters in the widget menu. We’ll also add custom variables like $before_widget, $after_widget, $before_title, and $after_title.