How do you create a custom widget in WordPress?

Custom widgets allow developers to create reusable content blocks. By extending the WP_Widget class, developers can define widget settings, form fields, and display output.

class Custom_Widget extends WP_Widget {
    function __construct() {
        parent::__construct('custom_widget', __('Custom Widget'));
    }
    public function widget($args, $instance) {
        echo $args['before_widget'] . 'Hello, World!' . $args['after_widget'];
    }
}
add_action('widgets_init', function() {
    register_widget('Custom_Widget');
});