How to create new widget in wordpress

Creating a new widget in WordPress involves several steps:

Step 1: Create a new PHP file

Create a new file in the wp-content/plugins directory of your WordPress installation. Name the file something like my_widget.php.

Step 2: Define the widget class

In the my_widget.php file, define a new class that extends the WP_Widget class. For example:

class My_Widget extends WP_Widget {
    // widget code goes here
}

Step 3: Define the widget's settings

In the My_Widget class, define the settings for your widget. This includes the widget's title, description, and any other settings you want to provide. For example:

function My_Widget() {
    $widget_ops = array('classname' => 'my_widget', 'description' => 'My Widget');
    parent::__construct('my_widget', 'My Widget', $widget_ops);
}

Step 4: Define the widget's output

In the My_Widget class, define the output for your widget. This is the code that will be displayed in the widget area. For example:

function widget($args, $instance) {
    // widget output code goes here
    echo '<p>Hello, World!</p>';
}

Step 5: Register the widget

In the my_widget.php file, register the widget using the wp_register_widget function. For example:

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

Step 6: Activate the plugin

Activate the plugin by going to the WordPress admin dashboard and clicking on the "Plugins" menu. Find the plugin you just created and click the "Activate" button.

Step 7: Add the widget to a widget area

Go to the WordPress admin dashboard and click on the "Appearance" menu. Click on the "Widgets" tab and drag and drop the new widget into a widget area.

That's it! Your new widget should now be displayed in the widget area.

Here is the complete code for a simple widget:

<?php
/*
Plugin Name: My Widget
Description: A simple widget that displays a message
*/

class My_Widget extends WP_Widget {
    function My_Widget() {
        $widget_ops = array('classname' => 'my_widget', 'description' => 'My Widget');
        parent::__construct('my_widget', 'My Widget', $widget_ops);
    }

    function widget($args, $instance) {
        echo '<p>Hello, World!</p>';
    }
}

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

Note: This is a very basic example, and you can customize the widget to suit your needs. You can also add more functionality to the widget by using WordPress's built-in functions and hooks.