3 * Widget API: WP_Widget base class
11 * Core base class extended to register widgets.
13 * This class must be extended for each widget, and WP_Widget::widget() must be overridden.
15 * If adding widget options, WP_Widget::update() and WP_Widget::form() should also be overridden.
18 * @since 4.4.0 Moved to its own file from wp-includes/widgets.php
23 * Root ID for all widgets of this type.
32 * Name for this widget type.
41 * Option name for this widget type.
50 * Alt option name for this widget type.
56 public $alt_option_name;
59 * Option array passed to wp_register_sidebar_widget().
65 public $widget_options;
68 * Option array passed to wp_register_widget_control().
74 public $control_options;
77 * Unique ID number of the current instance.
83 public $number = false;
86 * Unique ID string of the current instance (id_base-number).
95 * Whether the widget data has been updated.
97 * Set to true when the data is updated after a POST submit - ensures it does
104 public $updated = false;
107 // Member functions that must be overridden by subclasses.
111 * Echoes the widget content.
113 * Sub-classes should over-ride this function to generate their widget code.
118 * @param array $args Display arguments including 'before_title', 'after_title',
119 * 'before_widget', and 'after_widget'.
120 * @param array $instance The settings for the particular instance of the widget.
122 public function widget( $args, $instance ) {
123 die('function WP_Widget::widget() must be over-ridden in a sub-class.');
127 * Updates a particular instance of a widget.
129 * This function should check that `$new_instance` is set correctly. The newly-calculated
130 * value of `$instance` should be returned. If false is returned, the instance won't be
136 * @param array $new_instance New settings for this instance as input by the user via
138 * @param array $old_instance Old settings for this instance.
139 * @return array Settings to save or bool false to cancel saving.
141 public function update( $new_instance, $old_instance ) {
142 return $new_instance;
146 * Outputs the settings update form.
151 * @param array $instance Current settings.
152 * @return string Default return is 'noform'.
154 public function form( $instance ) {
155 echo '<p class="no-options-widget">' . __('There are no options for this widget.') . '</p>';
159 // Functions you'll need to call.
167 * @param string $id_base Optional Base ID for the widget, lowercase and unique. If left empty,
168 * a portion of the widget's class name will be used Has to be unique.
169 * @param string $name Name for the widget displayed on the configuration page.
170 * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for information
171 * on accepted arguments. Default empty array.
172 * @param array $control_options Optional. Widget control options. See wp_register_widget_control() for
173 * information on accepted arguments. Default empty array.
175 public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
176 $this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base);
178 $this->option_name = 'widget_' . $this->id_base;
179 $this->widget_options = wp_parse_args( $widget_options, array( 'classname' => $this->option_name, 'customize_selective_refresh' => false ) );
180 $this->control_options = wp_parse_args( $control_options, array( 'id_base' => $this->id_base ) );
191 * @param string $id_base Optional Base ID for the widget, lowercase and unique. If left empty,
192 * a portion of the widget's class name will be used Has to be unique.
193 * @param string $name Name for the widget displayed on the configuration page.
194 * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for information
195 * on accepted arguments. Default empty array.
196 * @param array $control_options Optional. Widget control options. See wp_register_widget_control() for
197 * information on accepted arguments. Default empty array.
199 public function WP_Widget( $id_base, $name, $widget_options = array(), $control_options = array() ) {
200 _deprecated_constructor( 'WP_Widget', '4.3.0', get_class( $this ) );
201 WP_Widget::__construct( $id_base, $name, $widget_options, $control_options );
205 * Constructs name attributes for use in form() fields
207 * This function should be used in form() methods to create name attributes for fields
208 * to be saved by update()
211 * @since 4.4.0 Array format field names are now accepted.
214 * @param string $field_name Field name
215 * @return string Name attribute for $field_name
217 public function get_field_name($field_name) {
218 if ( false === $pos = strpos( $field_name, '[' ) ) {
219 return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
221 return 'widget-' . $this->id_base . '[' . $this->number . '][' . substr_replace( $field_name, '][', $pos, strlen( '[' ) );
226 * Constructs id attributes for use in WP_Widget::form() fields.
228 * This function should be used in form() methods to create id attributes
229 * for fields to be saved by WP_Widget::update().
232 * @since 4.4.0 Array format field IDs are now accepted.
235 * @param string $field_name Field name.
236 * @return string ID attribute for `$field_name`.
238 public function get_field_id( $field_name ) {
239 return 'widget-' . $this->id_base . '-' . $this->number . '-' . trim( str_replace( array( '[]', '[', ']' ), array( '', '-', '' ), $field_name ), '-' );
243 * Register all widget instances of this widget class.
248 public function _register() {
249 $settings = $this->get_settings();
252 // When $settings is an array-like object, get an intrinsic array for use with array_keys().
253 if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
254 $settings = $settings->getArrayCopy();
257 if ( is_array( $settings ) ) {
258 foreach ( array_keys( $settings ) as $number ) {
259 if ( is_numeric( $number ) ) {
260 $this->_set( $number );
261 $this->_register_one( $number );
268 // If there are none, we register the widget's existence with a generic template.
270 $this->_register_one();
275 * Sets the internal order number for the widget instance.
280 * @param int $number The unique order number of this widget instance compared to other
281 * instances of the same class.
283 public function _set($number) {
284 $this->number = $number;
285 $this->id = $this->id_base . '-' . $number;
289 * Retrieves the widget display callback.
294 * @return callable Display callback.
296 public function _get_display_callback() {
297 return array($this, 'display_callback');
301 * Retrieves the widget update callback.
306 * @return callable Update callback.
308 public function _get_update_callback() {
309 return array($this, 'update_callback');
313 * Retrieves the form callback.
318 * @return callable Form callback.
320 public function _get_form_callback() {
321 return array($this, 'form_callback');
325 * Determines whether the current request is inside the Customizer preview.
327 * If true -- the current request is inside the Customizer preview, then
328 * the object cache gets suspended and widgets should check this to decide
329 * whether they should store anything persistently to the object cache,
330 * to transients, or anywhere else.
335 * @global WP_Customize_Manager $wp_customize
337 * @return bool True if within the Customizer preview, false if not.
339 public function is_preview() {
340 global $wp_customize;
341 return ( isset( $wp_customize ) && $wp_customize->is_preview() ) ;
345 * Generates the actual widget content (Do NOT override).
347 * Finds the instance and calls WP_Widget::widget().
352 * @param array $args Display arguments. See WP_Widget::widget() for information
353 * on accepted arguments.
354 * @param int|array $widget_args {
355 * Optional. Internal order number of the widget instance, or array of multi-widget arguments.
358 * @type int $number Number increment used for multiples of the same widget.
361 public function display_callback( $args, $widget_args = 1 ) {
362 if ( is_numeric( $widget_args ) ) {
363 $widget_args = array( 'number' => $widget_args );
366 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
367 $this->_set( $widget_args['number'] );
368 $instances = $this->get_settings();
370 if ( array_key_exists( $this->number, $instances ) ) {
371 $instance = $instances[ $this->number ];
374 * Filters the settings for a particular widget instance.
376 * Returning false will effectively short-circuit display of the widget.
380 * @param array $instance The current widget instance's settings.
381 * @param WP_Widget $this The current widget instance.
382 * @param array $args An array of default widget arguments.
384 $instance = apply_filters( 'widget_display_callback', $instance, $this, $args );
386 if ( false === $instance ) {
390 $was_cache_addition_suspended = wp_suspend_cache_addition();
391 if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
392 wp_suspend_cache_addition( true );
395 $this->widget( $args, $instance );
397 if ( $this->is_preview() ) {
398 wp_suspend_cache_addition( $was_cache_addition_suspended );
404 * Handles changed settings (Do NOT override).
409 * @global array $wp_registered_widgets
411 * @param int $deprecated Not used.
413 public function update_callback( $deprecated = 1 ) {
414 global $wp_registered_widgets;
416 $all_instances = $this->get_settings();
418 // We need to update the data
419 if ( $this->updated )
422 if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) {
423 // Delete the settings for this instance of the widget
424 if ( isset($_POST['the-widget-id']) )
425 $del_id = $_POST['the-widget-id'];
429 if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) {
430 $number = $wp_registered_widgets[$del_id]['params'][0]['number'];
432 if ( $this->id_base . '-' . $number == $del_id )
433 unset($all_instances[$number]);
436 if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) {
437 $settings = $_POST['widget-' . $this->id_base];
438 } elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) {
439 $num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
440 $settings = array( $num => array() );
445 foreach ( $settings as $number => $new_instance ) {
446 $new_instance = stripslashes_deep($new_instance);
447 $this->_set($number);
449 $old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array();
451 $was_cache_addition_suspended = wp_suspend_cache_addition();
452 if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
453 wp_suspend_cache_addition( true );
456 $instance = $this->update( $new_instance, $old_instance );
458 if ( $this->is_preview() ) {
459 wp_suspend_cache_addition( $was_cache_addition_suspended );
463 * Filters a widget's settings before saving.
465 * Returning false will effectively short-circuit the widget's ability
466 * to update settings.
470 * @param array $instance The current widget instance's settings.
471 * @param array $new_instance Array of new widget settings.
472 * @param array $old_instance Array of old widget settings.
473 * @param WP_Widget $this The current widget instance.
475 $instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this );
476 if ( false !== $instance ) {
477 $all_instances[$number] = $instance;
480 break; // run only once
484 $this->save_settings($all_instances);
485 $this->updated = true;
489 * Generates the widget control form (Do NOT override).
494 * @param int|array $widget_args {
495 * Optional. Internal order number of the widget instance, or array of multi-widget arguments.
498 * @type int $number Number increment used for multiples of the same widget.
500 * @return string|null
502 public function form_callback( $widget_args = 1 ) {
503 if ( is_numeric($widget_args) )
504 $widget_args = array( 'number' => $widget_args );
506 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
507 $all_instances = $this->get_settings();
509 if ( -1 == $widget_args['number'] ) {
510 // We echo out a form where 'number' can be set later
511 $this->_set('__i__');
514 $this->_set($widget_args['number']);
515 $instance = $all_instances[ $widget_args['number'] ];
519 * Filters the widget instance's settings before displaying the control form.
521 * Returning false effectively short-circuits display of the control form.
525 * @param array $instance The current widget instance's settings.
526 * @param WP_Widget $this The current widget instance.
528 $instance = apply_filters( 'widget_form_callback', $instance, $this );
531 if ( false !== $instance ) {
532 $return = $this->form($instance);
535 * Fires at the end of the widget control form.
537 * Use this hook to add extra fields to the widget form. The hook
538 * is only fired if the value passed to the 'widget_form_callback'
541 * Note: If the widget has no form, the text echoed from the default
542 * form method can be hidden using CSS.
546 * @param WP_Widget $this The widget instance, passed by reference.
547 * @param null $return Return null if new fields are added.
548 * @param array $instance An array of the widget's settings.
550 do_action_ref_array( 'in_widget_form', array( &$this, &$return, $instance ) );
556 * Registers an instance of the widget class.
561 * @param integer $number Optional. The unique order number of this widget instance
562 * compared to other instances of the same class. Default -1.
564 public function _register_one( $number = -1 ) {
565 wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
566 _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
567 _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
571 * Saves the settings for all instances of the widget class.
576 * @param array $settings Multi-dimensional array of widget instance settings.
578 public function save_settings( $settings ) {
579 $settings['_multiwidget'] = 1;
580 update_option( $this->option_name, $settings );
584 * Retrieves the settings for all instances of the widget class.
589 * @return array Multi-dimensional array of widget instance settings.
591 public function get_settings() {
593 $settings = get_option( $this->option_name );
595 if ( false === $settings ) {
596 if ( isset( $this->alt_option_name ) ) {
597 $settings = get_option( $this->alt_option_name );
599 // Save an option so it can be autoloaded next time.
600 $this->save_settings( array() );
604 if ( ! is_array( $settings ) && ! ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) ) {
608 if ( ! empty( $settings ) && ! isset( $settings['_multiwidget'] ) ) {
609 // Old format, convert if single widget.
610 $settings = wp_convert_widget_settings( $this->id_base, $this->option_name, $settings );
613 unset( $settings['_multiwidget'], $settings['__i__'] );