Today we’ll discuss on WordPress widget. How to code a widget for your custom plugin. Firstly you should be aware about the PHP and WordPress functions and some OOP’s concept. The functions used in widget creation are by default declares under WP_Widget class, we will discuss on that. First of all you should know about the widget creation.
- Create a seperate php file or use functions.php
- It is better to use the OOP’s concept for widget creation i.e code the widget in custom class.
- Create a class named as my_custom_widget and this class will extends the functionality of parent class i.e WP_Widget
class my_custom_widget extends WP_Widget{
}
- After class declaration create constructor for the class:
i.e, class my_custom_widget extends WP_Widget{
function __constructor(){
/*This will inherit the parent class i.e WP_Widget, constructor to my_custom_widget constructor*/
parent::__construct(‘my_custom_widget‘, $name=__(‘widget_name’), array(‘description’=>__(‘Custom Widget Creation Description’)));
}
}
- Similarly you have to create the following functions in class my_custom_widget after ‘constructor’ function
function form(){
/*This function will display the contents in widget. It outputs the settings in widget*/
}
function update(){
/*Update the settings value for widget*/
}
function widget(){
/*Display the widget settings output in frontend i.e in sidebar or wherever you put your widget*/
}
- After all these functions you have to register your widget so place the code after class:
add_action(‘widgets_init‘, function(){
register_widget(‘my_custom_widget‘);
});