How to create a custom WordPress widget


Do you want to create your own custom widgets in WordPress? Widgets allow you to add elements not contained in a sidebar or any area designated for widgets on your website.

You can use widgets to add banners, advertisements, newsletter subscription forms, and other elements to your website.

In this article, we will show you how to create a custom WordPress widget, step by step.

WHAT IS A WORDPRESS WIDGET?

WordPress widgets contain pieces of code that you can add to your website’s sidebars or areas designated to accommodate widgets.

Think of them as modules that you can use to add various elements using a simple drag-and-drop interface.

By default, WordPress comes with a standard set of widgets that you can use with any WordPress theme. Check out our beginner’s guide on how to use widgets in WordPress.

WordPress Widget

WordPress also allows developers to create their own custom widgets.

Many premium WordPress themes and plugins come with custom widgets that you can add to sidebars.

For example, you can add a contact form module, a custom login module, or a photo gallery to a sidebar without writing any code.

That said, let’s see how to easily create your own custom widgets in WordPress.

CREATING A CUSTOM WIDGET IN WORDPRESS

If you are learning to develop in WordPress, you will need a local development environment. You can install WordPress on your computer (Mac or Windows).

There are different ways to add custom widget code in WordPress.

You can create a specific site plugin and paste your widget code there.

You can also paste the code into the Functions.php file of your theme. However, it will only be available when that particular theme is active.

In this tutorial, we will create a simple widget that greets visitors. The goal is to become familiar with the WordPress widget class.

Let’s get started.

CREATING A BASIC WORDPRESS WIDGET

WordPress comes with a built-in WordPress Widget class. Every new WordPress widget extends the WordPress Widget class.

There are 18 methods mentioned in the WordPress developer handbook that can be used with the WP Widget class.

However, for the sake of this tutorial, we will focus on the following methods.

  • __construct(): This is where we create the widget ID, title, and description.
  • widget: This is where we define the output generated by the widget.
  • form: This part of the code is where we create the form with widget options for the backend.
  • update: This is where we save the widget options to the database.

Let’s study the following code where we have used these four methods inside the WP_Widget class.

// Create the widget
class swp_widget extends WP_Widget {

    // Construct
    function __construct() {

    }

    // Widget front-end
    public function widget( $args, $instance ) {

    }

    // Widget Backend
    public function form( $instance ) {

    }

    // Updating widget replacing old instances with new
    public function update( $new_instance, $old_instance ) {

    }

    // End swp_widget class here
}

The final piece of code is where we will actually register the widget and load it within WordPress.

// Registering and loading widget
function swp_load_widget() {
    register_widget('swp_widget');
}
add_action('widgets_init', 'swp_load_widget');

Now let’s put it all together to create a basic WordPress widget.

You can copy and paste the following code into your custom plugin or the Functions.php file of your theme.

// Create the widget
class swp_widget extends WP_Widget {

    function __construct() {
        parent::__construct(
            // Base ID of the widget
            'swp_widget',
            // Name of the Widget
            __('Specialist WP Widget', 'swp_widget_domain'),
            // Widget Description
            array('description' => __('Sample Specialist WP Widget!', 'swp_widget_domain'),)
        );
    }

    // Widget front-end
    public function widget($args, $instance) {
        $title = apply_filters('widget_title', $instance['title']);

        // Before and after widget arguments are defined by the theme
        echo $args['before_widget'];
        if (!empty($title))
            echo $args['before_title'] . $title . $args['after_title'];

        // Here is where we see the output
        echo __('Hello World!', 'swp_widget_domain');
        echo $args

['after_widget'];
    }

    // Widget Backend
    public function form($instance) {
        if (isset($instance['title'])) {
            $title = $instance['title'];
        } else {
            $title = __('Title', 'swp_widget_domain');
        }
        // Widget admin form
    ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
            <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); ?>" />
        </p>
    <?php
    }

    // Update the 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;
    }

    // End swp_widget class
}

// Registering and loading widget
function swp_load_widget() {
    register_widget('swp_widget');
}
add_action('widgets_init', 'swp_load_widget');

After adding the code, you need to go to the Appearance » Widgets page. You will notice the new SpecialistWP widget in the list of available widgets. You need to drag this widget to a sidebar.

Widget Action

This widget has only one form field to fill in; you can add your text and click the Save button to save the changes.

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

Widget in Action

Now, let’s review the code again.

First of all, we registered “swp_widget” and loaded our custom widget. Next, we defined what that widget does and how to view the widget’s backend.

Finally, we defined how to handle changes made to the widget.

Now there are some things you might want to ask. For example, what is the purpose of swp_text_domain?

WordPress uses gettext to handle translation and localization. This swp_text_domain tells gettext to make a string available for translation.

If you are creating a custom widget for your theme, you can replace swp_text_domain with your theme’s text_domain.

We hope this article has helped you learn how to easily create a custom WordPress widget.

Happy development!