Creating a custom widget in WordPress

This code snippet adds a new widget called “My Custom Widget” to your site’s widget options. The widget is labeled as  “My Custom Widget”  and allows the user to add it to a sidebar or widget area on the site.

It outputs a custom footer message in the widget area of your WordPress site, wherever the widget is placed, like the sidebar or footer.

class tsCustomWidget extends WP_Widget {
    // Widget settings and initialization
    function __construct() {
        parent::__construct(
            'ts_custom_widget', 
            esc_html__('My Custom Widget', 'text_domain'), 
            array('description' => esc_html__('A Custom Widget', 'text_domain'))
        );
    }

    // Front-end display of widget
    public function widget($args, $instance) {
        echo $args['before_widget'];
        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }
        // Custom footer message
        echo '<p>Follow us for the latest updates, exclusive offers, and more!</p>';
        echo '<p>Contact us: [email protected]</p>';
        echo '<p>&copy; 2024 Your Store. All rights reserved.</p>';
        echo $args['after_widget'];
    }

    // Back-end widget form and update methods remain unchanged...
}

// Register the widget
function ts_register_custom_widget() {
    register_widget('tsCustomWidget');
}
add_action('widgets_init', 'ts_register_custom_widget');