An easy way to create widgets in WordPress
First: Require the WP_Widget_Ex
class.
require_once get_template_directory() . '/inc/wp_widget_ex.php';
Second: Build your widget's class.
class WP_Example_Widget extends WP_Widget_Ex {
/**
* Title in WP Admin Widgets area.
* @var string
*/
public $widget_title = 'Example Widget';
/**
* Description in WP Admin Widgets area.
* @var string
*/
public $widget_description = 'Your site’s best widget.';
/**
* Widget fields details.
* @var array
*/
public $widget_fields = [
// Key for identify the input (allow letters, numbers and underscores).
'title' => [
'The best widget', // Default value for the input.
'strip_tags|trim|esc_attr' // Callbacks functions to format the input.
],
'text' => [
'Lorem ipsum dolor sit amet.',
'strip_tags'
],
];
/**
* Widget fields inputs.
* @var array
*/
public $widget_fields_inputs = [
// Key. The same of the "$this->widget_fields" var.
'title' => [
'Title', // Label for the input
'<input class="widefat" id="%1$s" name="%2$s" type="text" value="%3$s" />' // Input HTML.
],
'text' => [
'Text',
'<textarea class="widefat" id="%1$s" name="%2$s">%3$s</textarea>'
],
];
/**
* Function to show the widget in the front-end area.
*
* @param array $args
* @param array $instance
* @return void
*/
public function widget($args, $instance)
{
$widget_fields = $this->get_fields($instance);
echo $args['before_widget'];
echo $args['before_title'], $widget_fields['title'], $args['after_title'];
echo '<p>', $widget_fields['text'], '</p>';
echo $args['after_widget'];
}
}
Last: Register your widget.
add_action('widgets_init', function(){
register_widget('WP_Example_Widget');
});