Using WordPress ‘register_widget_control()’ PHP function

The register_widget_control() WordPress PHP function registers a widget control callback for customizing options.

Usage

register_widget_control($name, $control_callback, $width, $height, $params);

Parameters

  • $name (int|string) – Required. Sidebar ID.
  • $control_callback (callable) – Required. Widget control callback to display and process the form.
  • $width (int) – Optional. Widget width. Default: ”.
  • $height (int) – Optional. Widget height. Default: ”.
  • $params (mixed) – Required. Widget parameters.

More information

See WordPress Developer Resources: register_widget_control()

Examples

Register a simple text widget control

This example registers a simple text widget control with a form to update the widget title.

function my_text_widget_control($widget_args) {
  // Retrieve the widget options
  $options = get_option('my_text_widget_options');

  // Check if the form was submitted
  if (isset($_POST['my-text-widget-submit'])) {
    // Update the widget title
    $options['title'] = strip_tags(stripslashes($_POST['my-text-widget-title']));
    update_option('my_text_widget_options', $options);
  }

  // Display the widget control form
  echo '<p><label for="my-text-widget-title">Title: <input type="text" id="my-text-widget-title" name="my-text-widget-title" value="' . htmlspecialchars($options['title'], ENT_QUOTES) . '" /></label></p>';
  echo '<input type="hidden" name="my-text-widget-submit" id="my-text-widget-submit" value="1" />';
}

register_widget_control('My Text Widget', 'my_text_widget_control');

Register a custom image widget control

This example registers a custom image widget control with a form to update the image URL and caption.

function my_image_widget_control($widget_args) {
  // Retrieve the widget options
  $options = get_option('my_image_widget_options');

  // Check if the form was submitted
  if (isset($_POST['my-image-widget-submit'])) {
    // Update the image URL and caption
    $options['url'] = esc_url_raw($_POST['my-image-widget-url']);
    $options['caption'] = sanitize_text_field($_POST['my-image-widget-caption']);
    update_option('my_image_widget_options', $options);
  }

  // Display the widget control form
  echo '<p><label for="my-image-widget-url">Image URL: <input type="url" id="my-image-widget-url" name="my-image-widget-url" value="' . esc_attr($options['url']) . '" /></label></p>';
  echo '<p><label for="my-image-widget-caption">Caption: <input type="text" id="my-image-widget-caption" name="my-image-widget-caption" value="' . esc_attr($options['caption']) . '" /></label></p>';
  echo '<input type="hidden" name="my-image-widget-submit" id="my-image-widget-submit" value="1" />';
}

register_widget_control('My Image Widget', 'my_image_widget_control', 300, 200);