Creating a Custom Widget in WordPress

Paste the code in your theme’s functions.php file.

// Register and load the widget
function wpa_load_widget()
add_action('widgets_init', 'wpa_load_widget');

// Creating the widget 
class wpa_widget extends WP_Widget
    function __construct()
        // Base ID of your widget
        // Widget name will appear in UI
            __('wpaeginner Widget', 'wpa_widget_domain'), 
        // Widget description
            'description' => __('Sample widget', 'wpa_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 __('Hello, World!', 'wpa_widget_domain');
        echo $args['after_widget'];
    // Widget Backend 
    public function form($instance)
        if (isset($instance['title'])) {
            $title = $instance['title'];
        } else {
            $title = __('Wordpress Tutorials', 'wpa_widget_domain');
        // Widget admin form
   <label for="<?php
        echo $this->get_field_id('title');
   <input class="widefat" id="<?php
        echo $this->get_field_id('title');
?>" name="<?php
        echo $this->get_field_name('title');
?>" type="text" value="<?php
        echo esc_attr($title);
?>" />
    // Updating widget replacing old instances with new
    public function update($new_instance, $old_instance)
        $instance          = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        return $instance;
} // Class wpa_widget ends here ?>

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