[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-includes/ -> class-wp-widget.php (source)

   1  <?php
   2  /**
   3   * Widget API: WP_Widget base class
   4   *
   5   * @package WordPress
   6   * @subpackage Widgets
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Core base class extended to register widgets.
  12   *
  13   * This class must be extended for each widget, and WP_Widget::widget() must be overridden.
  14   *
  15   * If adding widget options, WP_Widget::update() and WP_Widget::form() should also be overridden.
  16   *
  17   * @since 2.8.0
  18   * @since 4.4.0 Moved to its own file from wp-includes/widgets.php
  19   */
  20  class WP_Widget {
  21  
  22      /**
  23       * Root ID for all widgets of this type.
  24       *
  25       * @since 2.8.0
  26       * @var mixed|string
  27       */
  28      public $id_base;
  29  
  30      /**
  31       * Name for this widget type.
  32       *
  33       * @since 2.8.0
  34       * @var string
  35       */
  36      public $name;
  37  
  38      /**
  39       * Option name for this widget type.
  40       *
  41       * @since 2.8.0
  42       * @var string
  43       */
  44      public $option_name;
  45  
  46      /**
  47       * Alt option name for this widget type.
  48       *
  49       * @since 2.8.0
  50       * @var string
  51       */
  52      public $alt_option_name;
  53  
  54      /**
  55       * Option array passed to wp_register_sidebar_widget().
  56       *
  57       * @since 2.8.0
  58       * @var array
  59       */
  60      public $widget_options;
  61  
  62      /**
  63       * Option array passed to wp_register_widget_control().
  64       *
  65       * @since 2.8.0
  66       * @var array
  67       */
  68      public $control_options;
  69  
  70      /**
  71       * Unique ID number of the current instance.
  72       *
  73       * @since 2.8.0
  74       * @var bool|int
  75       */
  76      public $number = false;
  77  
  78      /**
  79       * Unique ID string of the current instance (id_base-number).
  80       *
  81       * @since 2.8.0
  82       * @var bool|string
  83       */
  84      public $id = false;
  85  
  86      /**
  87       * Whether the widget data has been updated.
  88       *
  89       * Set to true when the data is updated after a POST submit - ensures it does
  90       * not happen twice.
  91       *
  92       * @since 2.8.0
  93       * @var bool
  94       */
  95      public $updated = false;
  96  
  97      //
  98      // Member functions that must be overridden by subclasses.
  99      //
 100  
 101      /**
 102       * Echoes the widget content.
 103       *
 104       * Sub-classes should over-ride this function to generate their widget code.
 105       *
 106       * @since 2.8.0
 107       *
 108       * @param array $args     Display arguments including 'before_title', 'after_title',
 109       *                        'before_widget', and 'after_widget'.
 110       * @param array $instance The settings for the particular instance of the widget.
 111       */
 112  	public function widget( $args, $instance ) {
 113          die( 'function WP_Widget::widget() must be over-ridden in a sub-class.' );
 114      }
 115  
 116      /**
 117       * Updates a particular instance of a widget.
 118       *
 119       * This function should check that `$new_instance` is set correctly. The newly-calculated
 120       * value of `$instance` should be returned. If false is returned, the instance won't be
 121       * saved/updated.
 122       *
 123       * @since 2.8.0
 124       *
 125       * @param array $new_instance New settings for this instance as input by the user via
 126       *                            WP_Widget::form().
 127       * @param array $old_instance Old settings for this instance.
 128       * @return array Settings to save or bool false to cancel saving.
 129       */
 130  	public function update( $new_instance, $old_instance ) {
 131          return $new_instance;
 132      }
 133  
 134      /**
 135       * Outputs the settings update form.
 136       *
 137       * @since 2.8.0
 138       *
 139       * @param array $instance Current settings.
 140       * @return string Default return is 'noform'.
 141       */
 142  	public function form( $instance ) {
 143          echo '<p class="no-options-widget">' . __( 'There are no options for this widget.' ) . '</p>';
 144          return 'noform';
 145      }
 146  
 147      // Functions you'll need to call.
 148  
 149      /**
 150       * PHP5 constructor.
 151       *
 152       * @since 2.8.0
 153       *
 154       * @param string $id_base         Optional Base ID for the widget, lowercase and unique. If left empty,
 155       *                                a portion of the widget's class name will be used Has to be unique.
 156       * @param string $name            Name for the widget displayed on the configuration page.
 157       * @param array  $widget_options  Optional. Widget options. See wp_register_sidebar_widget() for information
 158       *                                on accepted arguments. Default empty array.
 159       * @param array  $control_options Optional. Widget control options. See wp_register_widget_control() for
 160       *                                information on accepted arguments. Default empty array.
 161       */
 162  	public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
 163          $this->id_base         = empty( $id_base ) ? preg_replace( '/(wp_)?widget_/', '', strtolower( get_class( $this ) ) ) : strtolower( $id_base );
 164          $this->name            = $name;
 165          $this->option_name     = 'widget_' . $this->id_base;
 166          $this->widget_options  = wp_parse_args(
 167              $widget_options,
 168              array(
 169                  'classname'                   => $this->option_name,
 170                  'customize_selective_refresh' => false,
 171              )
 172          );
 173          $this->control_options = wp_parse_args( $control_options, array( 'id_base' => $this->id_base ) );
 174      }
 175  
 176      /**
 177       * PHP4 constructor.
 178       *
 179       * @since 2.8.0
 180       *
 181       * @see __construct()
 182       *
 183       * @param string $id_base         Optional Base ID for the widget, lowercase and unique. If left empty,
 184       *                                a portion of the widget's class name will be used Has to be unique.
 185       * @param string $name            Name for the widget displayed on the configuration page.
 186       * @param array  $widget_options  Optional. Widget options. See wp_register_sidebar_widget() for information
 187       *                                on accepted arguments. Default empty array.
 188       * @param array  $control_options Optional. Widget control options. See wp_register_widget_control() for
 189       *                                information on accepted arguments. Default empty array.
 190       */
 191  	public function WP_Widget( $id_base, $name, $widget_options = array(), $control_options = array() ) {
 192          _deprecated_constructor( 'WP_Widget', '4.3.0', get_class( $this ) );
 193          WP_Widget::__construct( $id_base, $name, $widget_options, $control_options );
 194      }
 195  
 196      /**
 197       * Constructs name attributes for use in form() fields
 198       *
 199       * This function should be used in form() methods to create name attributes for fields
 200       * to be saved by update()
 201       *
 202       * @since 2.8.0
 203       * @since 4.4.0 Array format field names are now accepted.
 204       *
 205       * @param string $field_name Field name
 206       * @return string Name attribute for $field_name
 207       */
 208  	public function get_field_name( $field_name ) {
 209          if ( false === $pos = strpos( $field_name, '[' ) ) {
 210              return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
 211          } else {
 212              return 'widget-' . $this->id_base . '[' . $this->number . '][' . substr_replace( $field_name, '][', $pos, strlen( '[' ) );
 213          }
 214      }
 215  
 216      /**
 217       * Constructs id attributes for use in WP_Widget::form() fields.
 218       *
 219       * This function should be used in form() methods to create id attributes
 220       * for fields to be saved by WP_Widget::update().
 221       *
 222       * @since 2.8.0
 223       * @since 4.4.0 Array format field IDs are now accepted.
 224       *
 225       * @param string $field_name Field name.
 226       * @return string ID attribute for `$field_name`.
 227       */
 228  	public function get_field_id( $field_name ) {
 229          return 'widget-' . $this->id_base . '-' . $this->number . '-' . trim( str_replace( array( '[]', '[', ']' ), array( '', '-', '' ), $field_name ), '-' );
 230      }
 231  
 232      /**
 233       * Register all widget instances of this widget class.
 234       *
 235       * @since 2.8.0
 236       */
 237  	public function _register() {
 238          $settings = $this->get_settings();
 239          $empty    = true;
 240  
 241          // When $settings is an array-like object, get an intrinsic array for use with array_keys().
 242          if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
 243              $settings = $settings->getArrayCopy();
 244          }
 245  
 246          if ( is_array( $settings ) ) {
 247              foreach ( array_keys( $settings ) as $number ) {
 248                  if ( is_numeric( $number ) ) {
 249                      $this->_set( $number );
 250                      $this->_register_one( $number );
 251                      $empty = false;
 252                  }
 253              }
 254          }
 255  
 256          if ( $empty ) {
 257              // If there are none, we register the widget's existence with a generic template.
 258              $this->_set( 1 );
 259              $this->_register_one();
 260          }
 261      }
 262  
 263      /**
 264       * Sets the internal order number for the widget instance.
 265       *
 266       * @since 2.8.0
 267       *
 268       * @param int $number The unique order number of this widget instance compared to other
 269       *                    instances of the same class.
 270       */
 271  	public function _set( $number ) {
 272          $this->number = $number;
 273          $this->id     = $this->id_base . '-' . $number;
 274      }
 275  
 276      /**
 277       * Retrieves the widget display callback.
 278       *
 279       * @since 2.8.0
 280       *
 281       * @return callable Display callback.
 282       */
 283  	public function _get_display_callback() {
 284          return array( $this, 'display_callback' );
 285      }
 286  
 287      /**
 288       * Retrieves the widget update callback.
 289       *
 290       * @since 2.8.0
 291       *
 292       * @return callable Update callback.
 293       */
 294  	public function _get_update_callback() {
 295          return array( $this, 'update_callback' );
 296      }
 297  
 298      /**
 299       * Retrieves the form callback.
 300       *
 301       * @since 2.8.0
 302       *
 303       * @return callable Form callback.
 304       */
 305  	public function _get_form_callback() {
 306          return array( $this, 'form_callback' );
 307      }
 308  
 309      /**
 310       * Determines whether the current request is inside the Customizer preview.
 311       *
 312       * If true -- the current request is inside the Customizer preview, then
 313       * the object cache gets suspended and widgets should check this to decide
 314       * whether they should store anything persistently to the object cache,
 315       * to transients, or anywhere else.
 316       *
 317       * @since 3.9.0
 318       *
 319       * @global WP_Customize_Manager $wp_customize
 320       *
 321       * @return bool True if within the Customizer preview, false if not.
 322       */
 323  	public function is_preview() {
 324          global $wp_customize;
 325          return ( isset( $wp_customize ) && $wp_customize->is_preview() );
 326      }
 327  
 328      /**
 329       * Generates the actual widget content (Do NOT override).
 330       *
 331       * Finds the instance and calls WP_Widget::widget().
 332       *
 333       * @since 2.8.0
 334       *
 335       * @param array     $args        Display arguments. See WP_Widget::widget() for information
 336       *                               on accepted arguments.
 337       * @param int|array $widget_args {
 338       *     Optional. Internal order number of the widget instance, or array of multi-widget arguments.
 339       *     Default 1.
 340       *
 341       *     @type int $number Number increment used for multiples of the same widget.
 342       * }
 343       */
 344  	public function display_callback( $args, $widget_args = 1 ) {
 345          if ( is_numeric( $widget_args ) ) {
 346              $widget_args = array( 'number' => $widget_args );
 347          }
 348  
 349          $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
 350          $this->_set( $widget_args['number'] );
 351          $instances = $this->get_settings();
 352  
 353          if ( array_key_exists( $this->number, $instances ) ) {
 354              $instance = $instances[ $this->number ];
 355  
 356              /**
 357               * Filters the settings for a particular widget instance.
 358               *
 359               * Returning false will effectively short-circuit display of the widget.
 360               *
 361               * @since 2.8.0
 362               *
 363               * @param array     $instance The current widget instance's settings.
 364               * @param WP_Widget $this     The current widget instance.
 365               * @param array     $args     An array of default widget arguments.
 366               */
 367              $instance = apply_filters( 'widget_display_callback', $instance, $this, $args );
 368  
 369              if ( false === $instance ) {
 370                  return;
 371              }
 372  
 373              $was_cache_addition_suspended = wp_suspend_cache_addition();
 374              if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
 375                  wp_suspend_cache_addition( true );
 376              }
 377  
 378              $this->widget( $args, $instance );
 379  
 380              if ( $this->is_preview() ) {
 381                  wp_suspend_cache_addition( $was_cache_addition_suspended );
 382              }
 383          }
 384      }
 385  
 386      /**
 387       * Handles changed settings (Do NOT override).
 388       *
 389       * @since 2.8.0
 390       *
 391       * @global array $wp_registered_widgets
 392       *
 393       * @param int $deprecated Not used.
 394       */
 395  	public function update_callback( $deprecated = 1 ) {
 396          global $wp_registered_widgets;
 397  
 398          $all_instances = $this->get_settings();
 399  
 400          // We need to update the data
 401          if ( $this->updated ) {
 402              return;
 403          }
 404  
 405          if ( isset( $_POST['delete_widget'] ) && $_POST['delete_widget'] ) {
 406              // Delete the settings for this instance of the widget
 407              if ( isset( $_POST['the-widget-id'] ) ) {
 408                  $del_id = $_POST['the-widget-id'];
 409              } else {
 410                  return;
 411              }
 412  
 413              if ( isset( $wp_registered_widgets[ $del_id ]['params'][0]['number'] ) ) {
 414                  $number = $wp_registered_widgets[ $del_id ]['params'][0]['number'];
 415  
 416                  if ( $this->id_base . '-' . $number == $del_id ) {
 417                      unset( $all_instances[ $number ] );
 418                  }
 419              }
 420          } else {
 421              if ( isset( $_POST[ 'widget-' . $this->id_base ] ) && is_array( $_POST[ 'widget-' . $this->id_base ] ) ) {
 422                  $settings = $_POST[ 'widget-' . $this->id_base ];
 423              } elseif ( isset( $_POST['id_base'] ) && $_POST['id_base'] == $this->id_base ) {
 424                  $num      = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
 425                  $settings = array( $num => array() );
 426              } else {
 427                  return;
 428              }
 429  
 430              foreach ( $settings as $number => $new_instance ) {
 431                  $new_instance = stripslashes_deep( $new_instance );
 432                  $this->_set( $number );
 433  
 434                  $old_instance = isset( $all_instances[ $number ] ) ? $all_instances[ $number ] : array();
 435  
 436                  $was_cache_addition_suspended = wp_suspend_cache_addition();
 437                  if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
 438                      wp_suspend_cache_addition( true );
 439                  }
 440  
 441                  $instance = $this->update( $new_instance, $old_instance );
 442  
 443                  if ( $this->is_preview() ) {
 444                      wp_suspend_cache_addition( $was_cache_addition_suspended );
 445                  }
 446  
 447                  /**
 448                   * Filters a widget's settings before saving.
 449                   *
 450                   * Returning false will effectively short-circuit the widget's ability
 451                   * to update settings.
 452                   *
 453                   * @since 2.8.0
 454                   *
 455                   * @param array     $instance     The current widget instance's settings.
 456                   * @param array     $new_instance Array of new widget settings.
 457                   * @param array     $old_instance Array of old widget settings.
 458                   * @param WP_Widget $this         The current widget instance.
 459                   */
 460                  $instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this );
 461                  if ( false !== $instance ) {
 462                      $all_instances[ $number ] = $instance;
 463                  }
 464  
 465                  break; // run only once
 466              }
 467          }
 468  
 469          $this->save_settings( $all_instances );
 470          $this->updated = true;
 471      }
 472  
 473      /**
 474       * Generates the widget control form (Do NOT override).
 475       *
 476       * @since 2.8.0
 477       *
 478       * @param int|array $widget_args {
 479       *     Optional. Internal order number of the widget instance, or array of multi-widget arguments.
 480       *     Default 1.
 481       *
 482       *     @type int $number Number increment used for multiples of the same widget.
 483       * }
 484       * @return string|null
 485       */
 486  	public function form_callback( $widget_args = 1 ) {
 487          if ( is_numeric( $widget_args ) ) {
 488              $widget_args = array( 'number' => $widget_args );
 489          }
 490  
 491          $widget_args   = wp_parse_args( $widget_args, array( 'number' => -1 ) );
 492          $all_instances = $this->get_settings();
 493  
 494          if ( -1 == $widget_args['number'] ) {
 495              // We echo out a form where 'number' can be set later
 496              $this->_set( '__i__' );
 497              $instance = array();
 498          } else {
 499              $this->_set( $widget_args['number'] );
 500              $instance = $all_instances[ $widget_args['number'] ];
 501          }
 502  
 503          /**
 504           * Filters the widget instance's settings before displaying the control form.
 505           *
 506           * Returning false effectively short-circuits display of the control form.
 507           *
 508           * @since 2.8.0
 509           *
 510           * @param array     $instance The current widget instance's settings.
 511           * @param WP_Widget $this     The current widget instance.
 512           */
 513          $instance = apply_filters( 'widget_form_callback', $instance, $this );
 514  
 515          $return = null;
 516          if ( false !== $instance ) {
 517              $return = $this->form( $instance );
 518  
 519              /**
 520               * Fires at the end of the widget control form.
 521               *
 522               * Use this hook to add extra fields to the widget form. The hook
 523               * is only fired if the value passed to the 'widget_form_callback'
 524               * hook is not false.
 525               *
 526               * Note: If the widget has no form, the text echoed from the default
 527               * form method can be hidden using CSS.
 528               *
 529               * @since 2.8.0
 530               *
 531               * @param WP_Widget $this     The widget instance (passed by reference).
 532               * @param null      $return   Return null if new fields are added.
 533               * @param array     $instance An array of the widget's settings.
 534               */
 535              do_action_ref_array( 'in_widget_form', array( &$this, &$return, $instance ) );
 536          }
 537          return $return;
 538      }
 539  
 540      /**
 541       * Registers an instance of the widget class.
 542       *
 543       * @since 2.8.0
 544       *
 545       * @param integer $number Optional. The unique order number of this widget instance
 546       *                        compared to other instances of the same class. Default -1.
 547       */
 548  	public function _register_one( $number = -1 ) {
 549          wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
 550          _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
 551          _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
 552      }
 553  
 554      /**
 555       * Saves the settings for all instances of the widget class.
 556       *
 557       * @since 2.8.0
 558       *
 559       * @param array $settings Multi-dimensional array of widget instance settings.
 560       */
 561  	public function save_settings( $settings ) {
 562          $settings['_multiwidget'] = 1;
 563          update_option( $this->option_name, $settings );
 564      }
 565  
 566      /**
 567       * Retrieves the settings for all instances of the widget class.
 568       *
 569       * @since 2.8.0
 570       *
 571       * @return array Multi-dimensional array of widget instance settings.
 572       */
 573  	public function get_settings() {
 574  
 575          $settings = get_option( $this->option_name );
 576  
 577          if ( false === $settings ) {
 578              if ( isset( $this->alt_option_name ) ) {
 579                  $settings = get_option( $this->alt_option_name );
 580              } else {
 581                  // Save an option so it can be autoloaded next time.
 582                  $this->save_settings( array() );
 583              }
 584          }
 585  
 586          if ( ! is_array( $settings ) && ! ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) ) {
 587              $settings = array();
 588          }
 589  
 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 );
 593          }
 594  
 595          unset( $settings['_multiwidget'], $settings['__i__'] );
 596          return $settings;
 597      }
 598  }


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7