How to create a custom wordpress widget

I’m going to show you how to create custom widget in wordpress.

Here is the code , Paste this code in your function.php file of your active child theme (or theme).

// Register and load the widget

add_action( 'widgets_init', 'register_my_widget' );
function register_my_widget() {
    register_widget( 'My_Widget' );
}

// Creating the widget
 
class My_Widget extends WP_Widget {
function __construct() {
parent::__construct(
 
// Base ID of your widget

'My_Widget', 
 
// Widget name will appear in UI

__('My Custom Widget', 'wpb_widget_domain'), 
 
// Widget description

array( 'description' => __( 'This is custom Widget', 'wpb_widget_domain' ), ) 
);
}
 
// Creating widget front-end
 
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
 
// before and after widget arguments are defined by themes

echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
 
// This is where you run the code and display the output

echo __( 'WP WordPress Site!', 'wpb_widget_domain' );
echo $args['after_widget'];
}
         
// Widget Backend 

public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}

// Widget admin form
?>

After adding the code you need to head over to Appearance » Widgets page. You will notice the new My Custom Widget in the list of available widgets. You need to drag and drop this widget to a sidebar.

Now you can visit your website to see it in action.

Leave a Comment

Scroll to Top