register_widget

Home » Functions » register_widget

The register_widget() function is a WordPress function used to register a widget for use within your WordPress theme or plugin. Widgets are small blocks of content that can be added to widget areas, such as sidebars or footers, to display specific information or functionality.

This function creates a new instance of the WP_Widget class and registers it with WordPress, allowing the widget to be added to the widget areas within your theme or plugin.

Once registered, the widget can be added to a widget area using the Appearance > Widgets screen in the WordPress dashboard.

Here is an example usage code:

class My_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'my_widget',
            __( 'My Widget', 'text_domain' ),
            array( 'description' => __( 'A custom widget for displaying my information', 'text_domain' ), )
        );
    }

    public function widget( $args, $instance ) {
        // Widget content goes here
    }

    public function form( $instance ) {
        // Widget form fields go here
    }
}

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

In this example, we are creating a new widget called "My Widget" that can be added to a widget area. The widget extends the WP_Widget class and includes a constructor, widget(), and form() method.

The register_my_widget() function is called using the widgets_init action hook, which registers the My_Widget class with WordPress using the register_widget() function.

Once registered, the widget can be added to a widget area using the Appearance > Widgets screen in the WordPress dashboard.

Learn More on WordPress.org

WordPress snippets using the register_widget function

Register an account to save your snippets or go Pro to get more features.