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(), WP_Widget::update()
14 * and WP_Widget::form() need to be overridden.
17 * @since 4.4.0 Moved to its own file from wp-includes/widgets.php
22 * Root ID for all widgets of this type.
31 * Name for this widget type.
40 * Option array passed to wp_register_sidebar_widget().
46 public $widget_options;
49 * Option array passed to wp_register_widget_control().
55 public $control_options;
58 * Unique ID number of the current instance.
64 public $number = false;
67 * Unique ID string of the current instance (id_base-number).
76 * Whether the widget data has been updated.
78 * Set to true when the data is updated after a POST submit - ensures it does
85 public $updated = false;
88 // Member functions that must be overriden by subclasses.
92 * Echoes the widget content.
94 * Sub-classes should over-ride this function to generate their widget code.
99 * @param array $args Display arguments including 'before_title', 'after_title',
100 * 'before_widget', and 'after_widget'.
101 * @param array $instance The settings for the particular instance of the widget.
103 public function widget( $args, $instance ) {
104 die('function WP_Widget::widget() must be over-ridden in a sub-class.');
108 * Updates a particular instance of a widget.
110 * This function should check that `$new_instance` is set correctly. The newly-calculated
111 * value of `$instance` should be returned. If false is returned, the instance won't be
117 * @param array $new_instance New settings for this instance as input by the user via
119 * @param array $old_instance Old settings for this instance.
120 * @return array Settings to save or bool false to cancel saving.
122 public function update( $new_instance, $old_instance ) {
123 return $new_instance;
127 * Outputs the settings update form.
132 * @param array $instance Current settings.
133 * @return string Default return is 'noform'.
135 public function form( $instance ) {
136 echo '<p class="no-options-widget">' . __('There are no options for this widget.') . '</p>';
140 // Functions you'll need to call.
148 * @param string $id_base Optional Base ID for the widget, lowercase and unique. If left empty,
149 * a portion of the widget's class name will be used Has to be unique.
150 * @param string $name Name for the widget displayed on the configuration page.
151 * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for information
152 * on accepted arguments. Default empty array.
153 * @param array $control_options Optional. Widget control options. See wp_register_widget_control() for
154 * information on accepted arguments. Default empty array.
156 public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
157 $this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base);
159 $this->option_name = 'widget_' . $this->id_base;
160 $this->widget_options = wp_parse_args( $widget_options, array( 'classname' => $this->option_name, 'customize_selective_refresh' => false ) );
161 $this->control_options = wp_parse_args( $control_options, array( 'id_base' => $this->id_base ) );
172 * @param string $id_base Optional Base ID for the widget, lowercase and unique. If left empty,
173 * a portion of the widget's class name will be used Has to be unique.
174 * @param string $name Name for the widget displayed on the configuration page.
175 * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for information
176 * on accepted arguments. Default empty array.
177 * @param array $control_options Optional. Widget control options. See wp_register_widget_control() for
178 * information on accepted arguments. Default empty array.
180 public function WP_Widget( $id_base, $name, $widget_options = array(), $control_options = array() ) {
181 _deprecated_constructor( 'WP_Widget', '4.3.0', get_class( $this ) );
182 WP_Widget::__construct( $id_base, $name, $widget_options, $control_options );
186 * Constructs name attributes for use in form() fields
188 * This function should be used in form() methods to create name attributes for fields
189 * to be saved by update()
192 * @since 4.4.0 Array format field names are now accepted.
195 * @param string $field_name Field name
196 * @return string Name attribute for $field_name
198 public function get_field_name($field_name) {
199 if ( false === $pos = strpos( $field_name, '[' ) ) {
200 return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
202 return 'widget-' . $this->id_base . '[' . $this->number . '][' . substr_replace( $field_name, '][', $pos, strlen( '[' ) );
207 * Constructs id attributes for use in WP_Widget::form() fields.
209 * This function should be used in form() methods to create id attributes
210 * for fields to be saved by WP_Widget::update().
213 * @since 4.4.0 Array format field IDs are now accepted.
216 * @param string $field_name Field name.
217 * @return string ID attribute for `$field_name`.
219 public function get_field_id( $field_name ) {
220 return 'widget-' . $this->id_base . '-' . $this->number . '-' . trim( str_replace( array( '[]', '[', ']' ), array( '', '-', '' ), $field_name ), '-' );
224 * Register all widget instances of this widget class.
229 public function _register() {
230 $settings = $this->get_settings();
233 // When $settings is an array-like object, get an intrinsic array for use with array_keys().
234 if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
235 $settings = $settings->getArrayCopy();
238 if ( is_array( $settings ) ) {
239 foreach ( array_keys( $settings ) as $number ) {
240 if ( is_numeric( $number ) ) {
241 $this->_set( $number );
242 $this->_register_one( $number );
249 // If there are none, we register the widget's existence with a generic template.
251 $this->_register_one();
256 * Sets the internal order number for the widget instance.
261 * @param int $number The unique order number of this widget instance compared to other
262 * instances of the same class.
264 public function _set($number) {
265 $this->number = $number;
266 $this->id = $this->id_base . '-' . $number;
270 * Retrieves the widget display callback.
275 * @return callable Display callback.
277 public function _get_display_callback() {
278 return array($this, 'display_callback');
282 * Retrieves the widget update callback.
287 * @return callable Update callback.
289 public function _get_update_callback() {
290 return array($this, 'update_callback');
294 * Retrieves the form callback.
299 * @return callable Form callback.
301 public function _get_form_callback() {
302 return array($this, 'form_callback');
306 * Determines whether the current request is inside the Customizer preview.
308 * If true -- the current request is inside the Customizer preview, then
309 * the object cache gets suspended and widgets should check this to decide
310 * whether they should store anything persistently to the object cache,
311 * to transients, or anywhere else.
316 * @global WP_Customize_Manager $wp_customize
318 * @return bool True if within the Customizer preview, false if not.
320 public function is_preview() {
321 global $wp_customize;
322 return ( isset( $wp_customize ) && $wp_customize->is_preview() ) ;
326 * Generates the actual widget content (Do NOT override).
328 * Finds the instance and calls WP_Widget::widget().
333 * @param array $args Display arguments. See WP_Widget::widget() for information
334 * on accepted arguments.
335 * @param int|array $widget_args {
336 * Optional. Internal order number of the widget instance, or array of multi-widget arguments.
339 * @type int $number Number increment used for multiples of the same widget.
342 public function display_callback( $args, $widget_args = 1 ) {
343 if ( is_numeric( $widget_args ) ) {
344 $widget_args = array( 'number' => $widget_args );
347 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
348 $this->_set( $widget_args['number'] );
349 $instances = $this->get_settings();
351 if ( array_key_exists( $this->number, $instances ) ) {
352 $instance = $instances[ $this->number ];
355 * Filter the settings for a particular widget instance.
357 * Returning false will effectively short-circuit display of the widget.
361 * @param array $instance The current widget instance's settings.
362 * @param WP_Widget $this The current widget instance.
363 * @param array $args An array of default widget arguments.
365 $instance = apply_filters( 'widget_display_callback', $instance, $this, $args );
367 if ( false === $instance ) {
371 $was_cache_addition_suspended = wp_suspend_cache_addition();
372 if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
373 wp_suspend_cache_addition( true );
376 $this->widget( $args, $instance );
378 if ( $this->is_preview() ) {
379 wp_suspend_cache_addition( $was_cache_addition_suspended );
385 * Handles changed settings (Do NOT override).
390 * @global array $wp_registered_widgets
392 * @param int $deprecated Not used.
394 public function update_callback( $deprecated = 1 ) {
395 global $wp_registered_widgets;
397 $all_instances = $this->get_settings();
399 // We need to update the data
400 if ( $this->updated )
403 if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) {
404 // Delete the settings for this instance of the widget
405 if ( isset($_POST['the-widget-id']) )
406 $del_id = $_POST['the-widget-id'];
410 if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) {
411 $number = $wp_registered_widgets[$del_id]['params'][0]['number'];
413 if ( $this->id_base . '-' . $number == $del_id )
414 unset($all_instances[$number]);
417 if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) {
418 $settings = $_POST['widget-' . $this->id_base];
419 } elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) {
420 $num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
421 $settings = array( $num => array() );
426 foreach ( $settings as $number => $new_instance ) {
427 $new_instance = stripslashes_deep($new_instance);
428 $this->_set($number);
430 $old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array();
432 $was_cache_addition_suspended = wp_suspend_cache_addition();
433 if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
434 wp_suspend_cache_addition( true );
437 $instance = $this->update( $new_instance, $old_instance );
439 if ( $this->is_preview() ) {
440 wp_suspend_cache_addition( $was_cache_addition_suspended );
444 * Filter a widget's settings before saving.
446 * Returning false will effectively short-circuit the widget's ability
447 * to update settings.
451 * @param array $instance The current widget instance's settings.
452 * @param array $new_instance Array of new widget settings.
453 * @param array $old_instance Array of old widget settings.
454 * @param WP_Widget $this The current widget instance.
456 $instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this );
457 if ( false !== $instance ) {
458 $all_instances[$number] = $instance;
461 break; // run only once
465 $this->save_settings($all_instances);
466 $this->updated = true;
470 * Generates the widget control form (Do NOT override).
475 * @param int|array $widget_args {
476 * Optional. Internal order number of the widget instance, or array of multi-widget arguments.
479 * @type int $number Number increment used for multiples of the same widget.
481 * @return string|null
483 public function form_callback( $widget_args = 1 ) {
484 if ( is_numeric($widget_args) )
485 $widget_args = array( 'number' => $widget_args );
487 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
488 $all_instances = $this->get_settings();
490 if ( -1 == $widget_args['number'] ) {
491 // We echo out a form where 'number' can be set later
492 $this->_set('__i__');
495 $this->_set($widget_args['number']);
496 $instance = $all_instances[ $widget_args['number'] ];
500 * Filter the widget instance's settings before displaying the control form.
502 * Returning false effectively short-circuits display of the control form.
506 * @param array $instance The current widget instance's settings.
507 * @param WP_Widget $this The current widget instance.
509 $instance = apply_filters( 'widget_form_callback', $instance, $this );
512 if ( false !== $instance ) {
513 $return = $this->form($instance);
516 * Fires at the end of the widget control form.
518 * Use this hook to add extra fields to the widget form. The hook
519 * is only fired if the value passed to the 'widget_form_callback'
522 * Note: If the widget has no form, the text echoed from the default
523 * form method can be hidden using CSS.
527 * @param WP_Widget $this The widget instance, passed by reference.
528 * @param null $return Return null if new fields are added.
529 * @param array $instance An array of the widget's settings.
531 do_action_ref_array( 'in_widget_form', array( &$this, &$return, $instance ) );
537 * Registers an instance of the widget class.
542 * @param integer $number Optional. The unique order number of this widget instance
543 * compared to other instances of the same class. Default -1.
545 public function _register_one( $number = -1 ) {
546 wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
547 _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
548 _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
552 * Saves the settings for all instances of the widget class.
557 * @param array $settings Multi-dimensional array of widget instance settings.
559 public function save_settings( $settings ) {
560 $settings['_multiwidget'] = 1;
561 update_option( $this->option_name, $settings );
565 * Retrieves the settings for all instances of the widget class.
570 * @return array Multi-dimensional array of widget instance settings.
572 public function get_settings() {
574 $settings = get_option( $this->option_name );
576 if ( false === $settings ) {
577 if ( isset( $this->alt_option_name ) ) {
578 $settings = get_option( $this->alt_option_name );
580 // Save an option so it can be autoloaded next time.
581 $this->save_settings( array() );
585 if ( ! is_array( $settings ) && ! ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) ) {
589 if ( ! empty( $settings ) && ! isset( $settings['_multiwidget'] ) ) {
590 // Old format, convert if single widget.
591 $settings = wp_convert_widget_settings( $this->id_base, $this->option_name, $settings );
594 unset( $settings['_multiwidget'], $settings['__i__'] );