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 overriden.
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 array passed to wp_register_sidebar_widget().
47 public $widget_options;
50 * Option array passed to wp_register_widget_control().
56 public $control_options;
59 * Unique ID number of the current instance.
65 public $number = false;
68 * Unique ID string of the current instance (id_base-number).
77 * Whether the widget data has been updated.
79 * Set to true when the data is updated after a POST submit - ensures it does
86 public $updated = false;
89 // Member functions that must be overriden by subclasses.
93 * Echoes the widget content.
95 * Sub-classes should over-ride this function to generate their widget code.
100 * @param array $args Display arguments including 'before_title', 'after_title',
101 * 'before_widget', and 'after_widget'.
102 * @param array $instance The settings for the particular instance of the widget.
104 public function widget( $args, $instance ) {
105 die('function WP_Widget::widget() must be over-ridden in a sub-class.');
109 * Updates a particular instance of a widget.
111 * This function should check that `$new_instance` is set correctly. The newly-calculated
112 * value of `$instance` should be returned. If false is returned, the instance won't be
118 * @param array $new_instance New settings for this instance as input by the user via
120 * @param array $old_instance Old settings for this instance.
121 * @return array Settings to save or bool false to cancel saving.
123 public function update( $new_instance, $old_instance ) {
124 return $new_instance;
128 * Outputs the settings update form.
133 * @param array $instance Current settings.
134 * @return string Default return is 'noform'.
136 public function form( $instance ) {
137 echo '<p class="no-options-widget">' . __('There are no options for this widget.') . '</p>';
141 // Functions you'll need to call.
149 * @param string $id_base Optional Base ID for the widget, lowercase and unique. If left empty,
150 * a portion of the widget's class name will be used Has to be unique.
151 * @param string $name Name for the widget displayed on the configuration page.
152 * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for information
153 * on accepted arguments. Default empty array.
154 * @param array $control_options Optional. Widget control options. See wp_register_widget_control() for
155 * information on accepted arguments. Default empty array.
157 public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
158 $this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base);
160 $this->option_name = 'widget_' . $this->id_base;
161 $this->widget_options = wp_parse_args( $widget_options, array( 'classname' => $this->option_name, 'customize_selective_refresh' => false ) );
162 $this->control_options = wp_parse_args( $control_options, array( 'id_base' => $this->id_base ) );
173 * @param string $id_base Optional Base ID for the widget, lowercase and unique. If left empty,
174 * a portion of the widget's class name will be used Has to be unique.
175 * @param string $name Name for the widget displayed on the configuration page.
176 * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for information
177 * on accepted arguments. Default empty array.
178 * @param array $control_options Optional. Widget control options. See wp_register_widget_control() for
179 * information on accepted arguments. Default empty array.
181 public function WP_Widget( $id_base, $name, $widget_options = array(), $control_options = array() ) {
182 _deprecated_constructor( 'WP_Widget', '4.3.0', get_class( $this ) );
183 WP_Widget::__construct( $id_base, $name, $widget_options, $control_options );
187 * Constructs name attributes for use in form() fields
189 * This function should be used in form() methods to create name attributes for fields
190 * to be saved by update()
193 * @since 4.4.0 Array format field names are now accepted.
196 * @param string $field_name Field name
197 * @return string Name attribute for $field_name
199 public function get_field_name($field_name) {
200 if ( false === $pos = strpos( $field_name, '[' ) ) {
201 return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
203 return 'widget-' . $this->id_base . '[' . $this->number . '][' . substr_replace( $field_name, '][', $pos, strlen( '[' ) );
208 * Constructs id attributes for use in WP_Widget::form() fields.
210 * This function should be used in form() methods to create id attributes
211 * for fields to be saved by WP_Widget::update().
214 * @since 4.4.0 Array format field IDs are now accepted.
217 * @param string $field_name Field name.
218 * @return string ID attribute for `$field_name`.
220 public function get_field_id( $field_name ) {
221 return 'widget-' . $this->id_base . '-' . $this->number . '-' . trim( str_replace( array( '[]', '[', ']' ), array( '', '-', '' ), $field_name ), '-' );
225 * Register all widget instances of this widget class.
230 public function _register() {
231 $settings = $this->get_settings();
234 // When $settings is an array-like object, get an intrinsic array for use with array_keys().
235 if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
236 $settings = $settings->getArrayCopy();
239 if ( is_array( $settings ) ) {
240 foreach ( array_keys( $settings ) as $number ) {
241 if ( is_numeric( $number ) ) {
242 $this->_set( $number );
243 $this->_register_one( $number );
250 // If there are none, we register the widget's existence with a generic template.
252 $this->_register_one();
257 * Sets the internal order number for the widget instance.
262 * @param int $number The unique order number of this widget instance compared to other
263 * instances of the same class.
265 public function _set($number) {
266 $this->number = $number;
267 $this->id = $this->id_base . '-' . $number;
271 * Retrieves the widget display callback.
276 * @return callable Display callback.
278 public function _get_display_callback() {
279 return array($this, 'display_callback');
283 * Retrieves the widget update callback.
288 * @return callable Update callback.
290 public function _get_update_callback() {
291 return array($this, 'update_callback');
295 * Retrieves the form callback.
300 * @return callable Form callback.
302 public function _get_form_callback() {
303 return array($this, 'form_callback');
307 * Determines whether the current request is inside the Customizer preview.
309 * If true -- the current request is inside the Customizer preview, then
310 * the object cache gets suspended and widgets should check this to decide
311 * whether they should store anything persistently to the object cache,
312 * to transients, or anywhere else.
317 * @global WP_Customize_Manager $wp_customize
319 * @return bool True if within the Customizer preview, false if not.
321 public function is_preview() {
322 global $wp_customize;
323 return ( isset( $wp_customize ) && $wp_customize->is_preview() ) ;
327 * Generates the actual widget content (Do NOT override).
329 * Finds the instance and calls WP_Widget::widget().
334 * @param array $args Display arguments. See WP_Widget::widget() for information
335 * on accepted arguments.
336 * @param int|array $widget_args {
337 * Optional. Internal order number of the widget instance, or array of multi-widget arguments.
340 * @type int $number Number increment used for multiples of the same widget.
343 public function display_callback( $args, $widget_args = 1 ) {
344 if ( is_numeric( $widget_args ) ) {
345 $widget_args = array( 'number' => $widget_args );
348 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
349 $this->_set( $widget_args['number'] );
350 $instances = $this->get_settings();
352 if ( array_key_exists( $this->number, $instances ) ) {
353 $instance = $instances[ $this->number ];
356 * Filters the settings for a particular widget instance.
358 * Returning false will effectively short-circuit display of the widget.
362 * @param array $instance The current widget instance's settings.
363 * @param WP_Widget $this The current widget instance.
364 * @param array $args An array of default widget arguments.
366 $instance = apply_filters( 'widget_display_callback', $instance, $this, $args );
368 if ( false === $instance ) {
372 $was_cache_addition_suspended = wp_suspend_cache_addition();
373 if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
374 wp_suspend_cache_addition( true );
377 $this->widget( $args, $instance );
379 if ( $this->is_preview() ) {
380 wp_suspend_cache_addition( $was_cache_addition_suspended );
386 * Handles changed settings (Do NOT override).
391 * @global array $wp_registered_widgets
393 * @param int $deprecated Not used.
395 public function update_callback( $deprecated = 1 ) {
396 global $wp_registered_widgets;
398 $all_instances = $this->get_settings();
400 // We need to update the data
401 if ( $this->updated )
404 if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) {
405 // Delete the settings for this instance of the widget
406 if ( isset($_POST['the-widget-id']) )
407 $del_id = $_POST['the-widget-id'];
411 if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) {
412 $number = $wp_registered_widgets[$del_id]['params'][0]['number'];
414 if ( $this->id_base . '-' . $number == $del_id )
415 unset($all_instances[$number]);
418 if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) {
419 $settings = $_POST['widget-' . $this->id_base];
420 } elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) {
421 $num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
422 $settings = array( $num => array() );
427 foreach ( $settings as $number => $new_instance ) {
428 $new_instance = stripslashes_deep($new_instance);
429 $this->_set($number);
431 $old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array();
433 $was_cache_addition_suspended = wp_suspend_cache_addition();
434 if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
435 wp_suspend_cache_addition( true );
438 $instance = $this->update( $new_instance, $old_instance );
440 if ( $this->is_preview() ) {
441 wp_suspend_cache_addition( $was_cache_addition_suspended );
445 * Filters a widget's settings before saving.
447 * Returning false will effectively short-circuit the widget's ability
448 * to update settings.
452 * @param array $instance The current widget instance's settings.
453 * @param array $new_instance Array of new widget settings.
454 * @param array $old_instance Array of old widget settings.
455 * @param WP_Widget $this The current widget instance.
457 $instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this );
458 if ( false !== $instance ) {
459 $all_instances[$number] = $instance;
462 break; // run only once
466 $this->save_settings($all_instances);
467 $this->updated = true;
471 * Generates the widget control form (Do NOT override).
476 * @param int|array $widget_args {
477 * Optional. Internal order number of the widget instance, or array of multi-widget arguments.
480 * @type int $number Number increment used for multiples of the same widget.
482 * @return string|null
484 public function form_callback( $widget_args = 1 ) {
485 if ( is_numeric($widget_args) )
486 $widget_args = array( 'number' => $widget_args );
488 $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
489 $all_instances = $this->get_settings();
491 if ( -1 == $widget_args['number'] ) {
492 // We echo out a form where 'number' can be set later
493 $this->_set('__i__');
496 $this->_set($widget_args['number']);
497 $instance = $all_instances[ $widget_args['number'] ];
501 * Filters the widget instance's settings before displaying the control form.
503 * Returning false effectively short-circuits display of the control form.
507 * @param array $instance The current widget instance's settings.
508 * @param WP_Widget $this The current widget instance.
510 $instance = apply_filters( 'widget_form_callback', $instance, $this );
513 if ( false !== $instance ) {
514 $return = $this->form($instance);
517 * Fires at the end of the widget control form.
519 * Use this hook to add extra fields to the widget form. The hook
520 * is only fired if the value passed to the 'widget_form_callback'
523 * Note: If the widget has no form, the text echoed from the default
524 * form method can be hidden using CSS.
528 * @param WP_Widget $this The widget instance, passed by reference.
529 * @param null $return Return null if new fields are added.
530 * @param array $instance An array of the widget's settings.
532 do_action_ref_array( 'in_widget_form', array( &$this, &$return, $instance ) );
538 * Registers an instance of the widget class.
543 * @param integer $number Optional. The unique order number of this widget instance
544 * compared to other instances of the same class. Default -1.
546 public function _register_one( $number = -1 ) {
547 wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
548 _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
549 _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
553 * Saves the settings for all instances of the widget class.
558 * @param array $settings Multi-dimensional array of widget instance settings.
560 public function save_settings( $settings ) {
561 $settings['_multiwidget'] = 1;
562 update_option( $this->option_name, $settings );
566 * Retrieves the settings for all instances of the widget class.
571 * @return array Multi-dimensional array of widget instance settings.
573 public function get_settings() {
575 $settings = get_option( $this->option_name );
577 if ( false === $settings ) {
578 if ( isset( $this->alt_option_name ) ) {
579 $settings = get_option( $this->alt_option_name );
581 // Save an option so it can be autoloaded next time.
582 $this->save_settings( array() );
586 if ( ! is_array( $settings ) && ! ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) ) {
590 if ( ! empty( $settings ) && ! isset( $settings['_multiwidget'] ) ) {
591 // Old format, convert if single widget.
592 $settings = wp_convert_widget_settings( $this->id_base, $this->option_name, $settings );
595 unset( $settings['_multiwidget'], $settings['__i__'] );