[ Index ]

PHP Cross Reference of WordPress

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          $pos = strpos( $field_name, '[' );
 210          if ( false === $pos ) {
 211              return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
 212          } else {
 213              return 'widget-' . $this->id_base . '[' . $this->number . '][' . substr_replace( $field_name, '][', $pos, strlen( '[' ) );
 214          }
 215      }
 216  
 217      /**
 218       * Constructs id attributes for use in WP_Widget::form() fields.
 219       *
 220       * This function should be used in form() methods to create id attributes
 221       * for fields to be saved by WP_Widget::update().
 222       *
 223       * @since 2.8.0
 224       * @since 4.4.0 Array format field IDs are now accepted.
 225       *
 226       * @param string $field_name Field name.
 227       * @return string ID attribute for `$field_name`.
 228       */
 229  	public function get_field_id( $field_name ) {
 230          return 'widget-' . $this->id_base . '-' . $this->number . '-' . trim( str_replace( array( '[]', '[', ']' ), array( '', '-', '' ), $field_name ), '-' );
 231      }
 232  
 233      /**
 234       * Register all widget instances of this widget class.
 235       *
 236       * @since 2.8.0
 237       */
 238  	public function _register() {
 239          $settings = $this->get_settings();
 240          $empty    = true;
 241  
 242          // When $settings is an array-like object, get an intrinsic array for use with array_keys().
 243          if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
 244              $settings = $settings->getArrayCopy();
 245          }
 246  
 247          if ( is_array( $settings ) ) {
 248              foreach ( array_keys( $settings ) as $number ) {
 249                  if ( is_numeric( $number ) ) {
 250                      $this->_set( $number );
 251                      $this->_register_one( $number );
 252                      $empty = false;
 253                  }
 254              }
 255          }
 256  
 257          if ( $empty ) {
 258              // If there are none, we register the widget's existence with a generic template.
 259              $this->_set( 1 );
 260              $this->_register_one();
 261          }
 262      }
 263  
 264      /**
 265       * Sets the internal order number for the widget instance.
 266       *
 267       * @since 2.8.0
 268       *
 269       * @param int $number The unique order number of this widget instance compared to other
 270       *                    instances of the same class.
 271       */
 272  	public function _set( $number ) {
 273          $this->number = $number;
 274          $this->id     = $this->id_base . '-' . $number;
 275      }
 276  
 277      /**
 278       * Retrieves the widget display callback.
 279       *
 280       * @since 2.8.0
 281       *
 282       * @return callable Display callback.
 283       */
 284  	public function _get_display_callback() {
 285          return array( $this, 'display_callback' );
 286      }
 287  
 288      /**
 289       * Retrieves the widget update callback.
 290       *
 291       * @since 2.8.0
 292       *
 293       * @return callable Update callback.
 294       */
 295  	public function _get_update_callback() {
 296          return array( $this, 'update_callback' );
 297      }
 298  
 299      /**
 300       * Retrieves the form callback.
 301       *
 302       * @since 2.8.0
 303       *
 304       * @return callable Form callback.
 305       */
 306  	public function _get_form_callback() {
 307          return array( $this, 'form_callback' );
 308      }
 309  
 310      /**
 311       * Determines whether the current request is inside the Customizer preview.
 312       *
 313       * If true -- the current request is inside the Customizer preview, then
 314       * the object cache gets suspended and widgets should check this to decide
 315       * whether they should store anything persistently to the object cache,
 316       * to transients, or anywhere else.
 317       *
 318       * @since 3.9.0
 319       *
 320       * @global WP_Customize_Manager $wp_customize
 321       *
 322       * @return bool True if within the Customizer preview, false if not.
 323       */
 324  	public function is_preview() {
 325          global $wp_customize;
 326          return ( isset( $wp_customize ) && $wp_customize->is_preview() );
 327      }
 328  
 329      /**
 330       * Generates the actual widget content (Do NOT override).
 331       *
 332       * Finds the instance and calls WP_Widget::widget().
 333       *
 334       * @since 2.8.0
 335       *
 336       * @param array     $args        Display arguments. See WP_Widget::widget() for information
 337       *                               on accepted arguments.
 338       * @param int|array $widget_args {
 339       *     Optional. Internal order number of the widget instance, or array of multi-widget arguments.
 340       *     Default 1.
 341       *
 342       *     @type int $number Number increment used for multiples of the same widget.
 343       * }
 344       */
 345  	public function display_callback( $args, $widget_args = 1 ) {
 346          if ( is_numeric( $widget_args ) ) {
 347              $widget_args = array( 'number' => $widget_args );
 348          }
 349  
 350          $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
 351          $this->_set( $widget_args['number'] );
 352          $instances = $this->get_settings();
 353  
 354          if ( array_key_exists( $this->number, $instances ) ) {
 355              $instance = $instances[ $this->number ];
 356  
 357              /**
 358               * Filters the settings for a particular widget instance.
 359               *
 360               * Returning false will effectively short-circuit display of the widget.
 361               *
 362               * @since 2.8.0
 363               *
 364               * @param array     $instance The current widget instance's settings.
 365               * @param WP_Widget $this     The current widget instance.
 366               * @param array     $args     An array of default widget arguments.
 367               */
 368              $instance = apply_filters( 'widget_display_callback', $instance, $this, $args );
 369  
 370              if ( false === $instance ) {
 371                  return;
 372              }
 373  
 374              $was_cache_addition_suspended = wp_suspend_cache_addition();
 375              if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
 376                  wp_suspend_cache_addition( true );
 377              }
 378  
 379              $this->widget( $args, $instance );
 380  
 381              if ( $this->is_preview() ) {
 382                  wp_suspend_cache_addition( $was_cache_addition_suspended );
 383              }
 384          }
 385      }
 386  
 387      /**
 388       * Handles changed settings (Do NOT override).
 389       *
 390       * @since 2.8.0
 391       *
 392       * @global array $wp_registered_widgets
 393       *
 394       * @param int $deprecated Not used.
 395       */
 396  	public function update_callback( $deprecated = 1 ) {
 397          global $wp_registered_widgets;
 398  
 399          $all_instances = $this->get_settings();
 400  
 401          // We need to update the data
 402          if ( $this->updated ) {
 403              return;
 404          }
 405  
 406          if ( isset( $_POST['delete_widget'] ) && $_POST['delete_widget'] ) {
 407              // Delete the settings for this instance of the widget
 408              if ( isset( $_POST['the-widget-id'] ) ) {
 409                  $del_id = $_POST['the-widget-id'];
 410              } else {
 411                  return;
 412              }
 413  
 414              if ( isset( $wp_registered_widgets[ $del_id ]['params'][0]['number'] ) ) {
 415                  $number = $wp_registered_widgets[ $del_id ]['params'][0]['number'];
 416  
 417                  if ( $this->id_base . '-' . $number == $del_id ) {
 418                      unset( $all_instances[ $number ] );
 419                  }
 420              }
 421          } else {
 422              if ( isset( $_POST[ 'widget-' . $this->id_base ] ) && is_array( $_POST[ 'widget-' . $this->id_base ] ) ) {
 423                  $settings = $_POST[ 'widget-' . $this->id_base ];
 424              } elseif ( isset( $_POST['id_base'] ) && $_POST['id_base'] == $this->id_base ) {
 425                  $num      = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
 426                  $settings = array( $num => array() );
 427              } else {
 428                  return;
 429              }
 430  
 431              foreach ( $settings as $number => $new_instance ) {
 432                  $new_instance = stripslashes_deep( $new_instance );
 433                  $this->_set( $number );
 434  
 435                  $old_instance = isset( $all_instances[ $number ] ) ? $all_instances[ $number ] : array();
 436  
 437                  $was_cache_addition_suspended = wp_suspend_cache_addition();
 438                  if ( $this->is_preview() && ! $was_cache_addition_suspended ) {
 439                      wp_suspend_cache_addition( true );
 440                  }
 441  
 442                  $instance = $this->update( $new_instance, $old_instance );
 443  
 444                  if ( $this->is_preview() ) {
 445                      wp_suspend_cache_addition( $was_cache_addition_suspended );
 446                  }
 447  
 448                  /**
 449                   * Filters a widget's settings before saving.
 450                   *
 451                   * Returning false will effectively short-circuit the widget's ability
 452                   * to update settings.
 453                   *
 454                   * @since 2.8.0
 455                   *
 456                   * @param array     $instance     The current widget instance's settings.
 457                   * @param array     $new_instance Array of new widget settings.
 458                   * @param array     $old_instance Array of old widget settings.
 459                   * @param WP_Widget $this         The current widget instance.
 460                   */
 461                  $instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this );
 462                  if ( false !== $instance ) {
 463                      $all_instances[ $number ] = $instance;
 464                  }
 465  
 466                  break; // run only once
 467              }
 468          }
 469  
 470          $this->save_settings( $all_instances );
 471          $this->updated = true;
 472      }
 473  
 474      /**
 475       * Generates the widget control form (Do NOT override).
 476       *
 477       * @since 2.8.0
 478       *
 479       * @param int|array $widget_args {
 480       *     Optional. Internal order number of the widget instance, or array of multi-widget arguments.
 481       *     Default 1.
 482       *
 483       *     @type int $number Number increment used for multiples of the same widget.
 484       * }
 485       * @return string|null
 486       */
 487  	public function form_callback( $widget_args = 1 ) {
 488          if ( is_numeric( $widget_args ) ) {
 489              $widget_args = array( 'number' => $widget_args );
 490          }
 491  
 492          $widget_args   = wp_parse_args( $widget_args, array( 'number' => -1 ) );
 493          $all_instances = $this->get_settings();
 494  
 495          if ( -1 == $widget_args['number'] ) {
 496              // We echo out a form where 'number' can be set later
 497              $this->_set( '__i__' );
 498              $instance = array();
 499          } else {
 500              $this->_set( $widget_args['number'] );
 501              $instance = $all_instances[ $widget_args['number'] ];
 502          }
 503  
 504          /**
 505           * Filters the widget instance's settings before displaying the control form.
 506           *
 507           * Returning false effectively short-circuits display of the control form.
 508           *
 509           * @since 2.8.0
 510           *
 511           * @param array     $instance The current widget instance's settings.
 512           * @param WP_Widget $this     The current widget instance.
 513           */
 514          $instance = apply_filters( 'widget_form_callback', $instance, $this );
 515  
 516          $return = null;
 517          if ( false !== $instance ) {
 518              $return = $this->form( $instance );
 519  
 520              /**
 521               * Fires at the end of the widget control form.
 522               *
 523               * Use this hook to add extra fields to the widget form. The hook
 524               * is only fired if the value passed to the 'widget_form_callback'
 525               * hook is not false.
 526               *
 527               * Note: If the widget has no form, the text echoed from the default
 528               * form method can be hidden using CSS.
 529               *
 530               * @since 2.8.0
 531               *
 532               * @param WP_Widget $this     The widget instance (passed by reference).
 533               * @param null      $return   Return null if new fields are added.
 534               * @param array     $instance An array of the widget's settings.
 535               */
 536              do_action_ref_array( 'in_widget_form', array( &$this, &$return, $instance ) );
 537          }
 538          return $return;
 539      }
 540  
 541      /**
 542       * Registers an instance of the widget class.
 543       *
 544       * @since 2.8.0
 545       *
 546       * @param integer $number Optional. The unique order number of this widget instance
 547       *                        compared to other instances of the same class. Default -1.
 548       */
 549  	public function _register_one( $number = -1 ) {
 550          wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
 551          _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
 552          _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
 553      }
 554  
 555      /**
 556       * Saves the settings for all instances of the widget class.
 557       *
 558       * @since 2.8.0
 559       *
 560       * @param array $settings Multi-dimensional array of widget instance settings.
 561       */
 562  	public function save_settings( $settings ) {
 563          $settings['_multiwidget'] = 1;
 564          update_option( $this->option_name, $settings );
 565      }
 566  
 567      /**
 568       * Retrieves the settings for all instances of the widget class.
 569       *
 570       * @since 2.8.0
 571       *
 572       * @return array Multi-dimensional array of widget instance settings.
 573       */
 574  	public function get_settings() {
 575  
 576          $settings = get_option( $this->option_name );
 577  
 578          if ( false === $settings ) {
 579              if ( isset( $this->alt_option_name ) ) {
 580                  $settings = get_option( $this->alt_option_name );
 581              } else {
 582                  // Save an option so it can be autoloaded next time.
 583                  $this->save_settings( array() );
 584              }
 585          }
 586  
 587          if ( ! is_array( $settings ) && ! ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) ) {
 588              $settings = array();
 589          }
 590  
 591          if ( ! empty( $settings ) && ! isset( $settings['_multiwidget'] ) ) {
 592              // Old format, convert if single widget.
 593              $settings = wp_convert_widget_settings( $this->id_base, $this->option_name, $settings );
 594          }
 595  
 596          unset( $settings['_multiwidget'], $settings['__i__'] );
 597          return $settings;
 598      }
 599  }


Generated: Tue Sep 17 01:00:03 2019 Cross-referenced by PHPXref 0.7.1