Using WordPress ‘register_widget()’ PHP function

The register_widget() WordPress PHP function registers a custom widget with WordPress.

Usage

register_widget('My_Custom_Widget');

Parameters

  • $widget (string|WP_Widget) – Required. Either the name of a WP_Widget subclass or an instance of a WP_Widget subclass.

More information

See WordPress Developer Resources: register_widget()

Examples

Register a Simple Text Widget

This code registers a simple text widget named “My Text Widget”:

class My_Text_Widget extends WP_Widget {
  function __construct() {
    parent::__construct(
      'my_text_widget',
      __('My Text Widget', 'text_domain')
    );
  }

function widget($args, $instance) { echo $args['before_widget']; echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title']; echo '<p>' . esc_html($instance['text']) . '</p>'; echo $args['after_widget']; }

function form($instance) { $title = !empty($instance['title']) ? $instance['title'] : __('New title', 'text_domain'); $text = !empty($instance['text']) ? $instance['text'] : __('New text', 'text_domain'); ?> <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> <p> <label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Text:'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" type="text" value="<?php echo esc_attr($text); ?>"> </p> <?php }

function update($new_instance, $old_instance) { $instance = array(); $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : ''; $instance['text'] = (!empty($new_instance['text'])) ? strip_tags($new_instance['text']) : ''; return $instance; } }

function register_my_text_widget() { register_widget('My_Text_Widget'); } add_action('widgets_init', 'register_my_text_widget');