[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-customize-setting.php (source)

   1  <?php
   2  /**
   3   * WordPress Customize Setting classes
   4   *
   5   * @package WordPress
   6   * @subpackage Customize
   7   * @since 3.4.0
   8   */
   9  
  10  // Don't load directly.
  11  if ( ! defined( 'ABSPATH' ) ) {
  12      exit;
  13  }
  14  
  15  /**
  16   * Customize Setting class.
  17   *
  18   * Handles saving and sanitizing of settings.
  19   *
  20   * @since 3.4.0
  21   *
  22   * @see WP_Customize_Manager
  23   * @link https://developer.wordpress.org/themes/customize-api
  24   */
  25  #[AllowDynamicProperties]
  26  class WP_Customize_Setting {
  27      /**
  28       * Customizer bootstrap instance.
  29       *
  30       * @since 3.4.0
  31       * @var WP_Customize_Manager
  32       */
  33      public $manager;
  34  
  35      /**
  36       * Unique string identifier for the setting.
  37       *
  38       * @since 3.4.0
  39       * @var string
  40       */
  41      public $id;
  42  
  43      /**
  44       * Type of customize settings.
  45       *
  46       * @since 3.4.0
  47       * @var string
  48       */
  49      public $type = 'theme_mod';
  50  
  51      /**
  52       * Capability required to edit this setting.
  53       *
  54       * @since 3.4.0
  55       * @var string|array
  56       */
  57      public $capability = 'edit_theme_options';
  58  
  59      /**
  60       * Theme features required to support the setting.
  61       *
  62       * @since 3.4.0
  63       * @var string|string[]
  64       */
  65      public $theme_supports = '';
  66  
  67      /**
  68       * The default value for the setting.
  69       *
  70       * @since 3.4.0
  71       * @var mixed
  72       */
  73      public $default = '';
  74  
  75      /**
  76       * Options for rendering the live preview of changes in Customizer.
  77       *
  78       * Set this value to 'postMessage' to enable a custom JavaScript handler to render changes to this setting
  79       * as opposed to reloading the whole page.
  80       *
  81       * @since 3.4.0
  82       * @var string
  83       */
  84      public $transport = 'refresh';
  85  
  86      /**
  87       * Server-side validation callback for the setting's value.
  88       *
  89       * An empty string means there is no callback.
  90       *
  91       * @since 4.6.0
  92       * @var callable|string
  93       * @phpstan-var (callable( WP_Error, mixed, WP_Customize_Setting ): mixed)|''
  94       */
  95      public $validate_callback = '';
  96  
  97      /**
  98       * Callback to filter a Customize setting value in un-slashed form.
  99       *
 100       * An empty string means there is no callback.
 101       *
 102       * @since 3.4.0
 103       * @var callable|string
 104       * @phpstan-var (callable( mixed, WP_Customize_Setting ): mixed)|''
 105       */
 106      public $sanitize_callback = '';
 107  
 108      /**
 109       * Callback to convert a Customize PHP setting value to a value that is JSON serializable.
 110       *
 111       * An empty string means there is no callback.
 112       *
 113       * @since 3.4.0
 114       * @var callable|string
 115       * @phpstan-var (callable( mixed, WP_Customize_Setting ): mixed)|''
 116       */
 117      public $sanitize_js_callback = '';
 118  
 119      /**
 120       * Whether or not the setting is initially dirty when created.
 121       *
 122       * This is used to ensure that a setting will be sent from the pane to the
 123       * preview when loading the Customizer. Normally a setting only is synced to
 124       * the preview if it has been changed. This allows the setting to be sent
 125       * from the start.
 126       *
 127       * @since 4.2.0
 128       * @var bool
 129       */
 130      public $dirty = false;
 131  
 132      /**
 133       * ID Data.
 134       *
 135       * @since 3.4.0
 136       * @var array
 137       */
 138      protected $id_data = array();
 139  
 140      /**
 141       * Whether or not preview() was called.
 142       *
 143       * @since 4.4.0
 144       * @var bool
 145       */
 146      protected $is_previewed = false;
 147  
 148      /**
 149       * Cache of multidimensional values to improve performance.
 150       *
 151       * @since 4.4.0
 152       * @var array
 153       */
 154      protected static $aggregated_multidimensionals = array();
 155  
 156      /**
 157       * Whether the multidimensional setting is aggregated.
 158       *
 159       * @since 4.4.0
 160       * @var bool
 161       */
 162      protected $is_multidimensional_aggregated = false;
 163  
 164      /**
 165       * Whether the setting is being saved.
 166       *
 167       * When saving, the value of an option setting is not sanitized with `sanitize_option()`
 168       * by {@see WP_Customize_Setting::sanitize()} since `update_option()` sanitizes it.
 169       *
 170       * @since 7.1.5
 171       * @var bool
 172       */
 173      private $is_saving = false;
 174  
 175      /**
 176       * Number of times that previewing has been suspended for each option, keyed by option name.
 177       *
 178       * While previewing an option is suspended, its preview filters pass through the original value.
 179       *
 180       * @since 7.1.5
 181       * @see WP_Customize_Setting::suspend_option_preview()
 182       * @var array<string, positive-int>
 183       */
 184      private static $suspended_option_previews = array();
 185  
 186      /**
 187       * Constructor.
 188       *
 189       * Any supplied $args override class property defaults.
 190       *
 191       * @since 3.4.0
 192       *
 193       * @param WP_Customize_Manager $manager Customizer bootstrap instance.
 194       * @param string               $id      A specific ID of the setting.
 195       *                                      Can be a theme mod or option name.
 196       * @param array                $args    {
 197       *     Optional. Array of properties for the new Setting object. Default empty array.
 198       *
 199       *     @type string          $type                 Type of the setting. Default 'theme_mod'.
 200       *     @type string          $capability           Capability required for the setting. Default 'edit_theme_options'
 201       *     @type string|string[] $theme_supports       Theme features required to support the panel. Default is none.
 202       *     @type mixed           $default              Default value for the setting. Default is empty string.
 203       *     @type string          $transport            Options for rendering the live preview of changes in Customizer.
 204       *                                                 Using 'refresh' makes the change visible by reloading the whole preview.
 205       *                                                 Using 'postMessage' allows a custom JavaScript to handle live changes.
 206       *                                                 Default is 'refresh'.
 207       *     @type callable        $validate_callback    Server-side validation callback for the setting's value.
 208       *     @type callable        $sanitize_callback    Callback to filter a Customize setting value in un-slashed form.
 209       *     @type callable        $sanitize_js_callback Callback to convert a Customize PHP setting value to a value that is
 210       *                                                 JSON serializable.
 211       *     @type bool            $dirty                Whether or not the setting is initially dirty when created.
 212       * }
 213       */
 214  	public function __construct( $manager, $id, $args = array() ) {
 215          $keys = array_keys( get_object_vars( $this ) );
 216          foreach ( $keys as $key ) {
 217              if ( isset( $args[ $key ] ) ) {
 218                  $this->$key = $args[ $key ];
 219              }
 220          }
 221  
 222          $this->manager = $manager;
 223          $this->id      = $id;
 224  
 225          // Parse the ID for array keys.
 226          $this->id_data['keys'] = preg_split( '/\[/', str_replace( ']', '', $this->id ) );
 227          $this->id_data['base'] = array_shift( $this->id_data['keys'] );
 228  
 229          // Rebuild the ID.
 230          $this->id = $this->id_data['base'];
 231          if ( ! empty( $this->id_data['keys'] ) ) {
 232              $this->id .= '[' . implode( '][', $this->id_data['keys'] ) . ']';
 233          }
 234  
 235          if ( $this->validate_callback ) {
 236              add_filter( "customize_validate_{$this->id}", $this->validate_callback, 10, 3 );
 237          }
 238          if ( $this->sanitize_callback ) {
 239              add_filter( "customize_sanitize_{$this->id}", $this->sanitize_callback, 10, 2 );
 240          }
 241          if ( $this->sanitize_js_callback ) {
 242              add_filter( "customize_sanitize_js_{$this->id}", $this->sanitize_js_callback, 10, 2 );
 243          }
 244  
 245          if ( 'option' === $this->type || 'theme_mod' === $this->type ) {
 246              // Other setting types can opt-in to aggregate multidimensional explicitly.
 247              $this->aggregate_multidimensional();
 248  
 249              // Allow option settings to indicate whether they should be autoloaded.
 250              if ( 'option' === $this->type && isset( $args['autoload'] ) ) {
 251                  self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload'] = $args['autoload'];
 252              }
 253          }
 254      }
 255  
 256      /**
 257       * Get parsed ID data for multidimensional setting.
 258       *
 259       * @since 4.4.0
 260       *
 261       * @return array {
 262       *     ID data for multidimensional setting.
 263       *
 264       *     @type string $base ID base
 265       *     @type array  $keys Keys for multidimensional array.
 266       * }
 267       */
 268  	final public function id_data() {
 269          return $this->id_data;
 270      }
 271  
 272      /**
 273       * Set up the setting for aggregated multidimensional values.
 274       *
 275       * When a multidimensional setting gets aggregated, all of its preview and update
 276       * calls get combined into one call, greatly improving performance.
 277       *
 278       * @since 4.4.0
 279       */
 280  	protected function aggregate_multidimensional() {
 281          $id_base = $this->id_data['base'];
 282          self::$aggregated_multidimensionals[ $this->type ] ??= array();
 283          if ( ! isset( self::$aggregated_multidimensionals[ $this->type ][ $id_base ] ) ) {
 284              self::$aggregated_multidimensionals[ $this->type ][ $id_base ] = array(
 285                  'previewed_instances'       => array(), // Calling preview() will add the $setting to the array.
 286                  'preview_applied_instances' => array(), // Flags for which settings have had their values applied.
 287                  'root_value'                => $this->get_root_value( array() ), // Root value for initial state, manipulated by preview and update calls.
 288              );
 289          }
 290  
 291          if ( ! empty( $this->id_data['keys'] ) ) {
 292              // Note the preview-applied flag is cleared at priority 9 to ensure it is cleared before a deferred-preview runs.
 293              add_action( "customize_post_value_set_{$this->id}", array( $this, '_clear_aggregated_multidimensional_preview_applied_flag' ), 9 );
 294              $this->is_multidimensional_aggregated = true;
 295          }
 296      }
 297  
 298      /**
 299       * Reset `$aggregated_multidimensionals` static variable.
 300       *
 301       * This is intended only for use by unit tests.
 302       *
 303       * @since 4.5.0
 304       * @ignore
 305       */
 306  	public static function reset_aggregated_multidimensionals() {
 307          self::$aggregated_multidimensionals = array();
 308      }
 309  
 310      /**
 311       * The ID for the current site when the preview() method was called.
 312       *
 313       * @since 4.2.0
 314       * @var int
 315       */
 316      protected $_previewed_blog_id;
 317  
 318      /**
 319       * Return true if the current site is not the same as the previewed site.
 320       *
 321       * @since 4.2.0
 322       *
 323       * @return bool If preview() has been called.
 324       */
 325  	public function is_current_blog_previewed() {
 326          if ( ! isset( $this->_previewed_blog_id ) ) {
 327              return false;
 328          }
 329          return ( get_current_blog_id() === $this->_previewed_blog_id );
 330      }
 331  
 332      /**
 333       * Original non-previewed value stored by the preview method.
 334       *
 335       * @see WP_Customize_Setting::preview()
 336       * @since 4.1.1
 337       * @var mixed
 338       */
 339      protected $_original_value;
 340  
 341      /**
 342       * Add filters to supply the setting's value when accessed.
 343       *
 344       * If the setting already has a pre-existing value and there is no incoming
 345       * post value for the setting, then this method will short-circuit since
 346       * there is no change to preview.
 347       *
 348       * @since 3.4.0
 349       * @since 4.4.0 Added boolean return value.
 350       *
 351       * @return bool False when preview short-circuits due no change needing to be previewed.
 352       */
 353  	public function preview() {
 354          if ( ! isset( $this->_previewed_blog_id ) ) {
 355              $this->_previewed_blog_id = get_current_blog_id();
 356          }
 357  
 358          // Prevent re-previewing an already-previewed setting.
 359          if ( $this->is_previewed ) {
 360              return true;
 361          }
 362  
 363          $id_base                 = $this->id_data['base'];
 364          $is_multidimensional     = ! empty( $this->id_data['keys'] );
 365          $multidimensional_filter = array( $this, '_multidimensional_preview_filter' );
 366  
 367          /*
 368           * Check if the setting has a pre-existing value (an isset check),
 369           * and if doesn't have any incoming post value. If both checks are true,
 370           * then the preview short-circuits because there is nothing that needs
 371           * to be previewed.
 372           */
 373          $undefined     = new stdClass();
 374          $needs_preview = ( $undefined !== $this->post_value( $undefined ) );
 375          $value         = null;
 376  
 377          // Since no post value was defined, check if we have an initial value set.
 378          if ( ! $needs_preview ) {
 379              if ( $this->is_multidimensional_aggregated ) {
 380                  $root  = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
 381                  $value = $this->multidimensional_get( $root, $this->id_data['keys'], $undefined );
 382              } else {
 383                  $default       = $this->default;
 384                  $this->default = $undefined; // Temporarily set default to undefined so we can detect if existing value is set.
 385                  $value         = $this->value();
 386                  $this->default = $default;
 387              }
 388              $needs_preview = ( $undefined === $value ); // Because the default needs to be supplied.
 389          }
 390  
 391          // If the setting does not need previewing now, defer to when it has a value to preview.
 392          if ( ! $needs_preview ) {
 393              if ( ! has_action( "customize_post_value_set_{$this->id}", array( $this, 'preview' ) ) ) {
 394                  add_action( "customize_post_value_set_{$this->id}", array( $this, 'preview' ) );
 395              }
 396              return false;
 397          }
 398  
 399          switch ( $this->type ) {
 400              case 'theme_mod':
 401                  if ( ! $is_multidimensional ) {
 402                      add_filter( "theme_mod_{$id_base}", array( $this, '_preview_filter' ) );
 403                  } else {
 404                      if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) {
 405                          // Only add this filter once for this ID base.
 406                          add_filter( "theme_mod_{$id_base}", $multidimensional_filter );
 407                      }
 408                      self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'][ $this->id ] = $this;
 409                  }
 410                  break;
 411              case 'option':
 412                  if ( ! $is_multidimensional ) {
 413                      add_filter( "pre_option_{$id_base}", array( $this, '_preview_filter' ) );
 414                  } else {
 415                      if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) {
 416                          // Only add these filters once for this ID base.
 417                          add_filter( "option_{$id_base}", $multidimensional_filter );
 418                          add_filter( "default_option_{$id_base}", $multidimensional_filter );
 419                      }
 420                      self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'][ $this->id ] = $this;
 421                  }
 422                  break;
 423              default:
 424                  /**
 425                   * Fires when the WP_Customize_Setting::preview() method is called for settings
 426                   * not handled as theme_mods or options.
 427                   *
 428                   * The dynamic portion of the hook name, `$this->id`, refers to the setting ID.
 429                   *
 430                   * @since 3.4.0
 431                   *
 432                   * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
 433                   */
 434                  do_action( "customize_preview_{$this->id}", $this );
 435  
 436                  /**
 437                   * Fires when the WP_Customize_Setting::preview() method is called for settings
 438                   * not handled as theme_mods or options.
 439                   *
 440                   * The dynamic portion of the hook name, `$this->type`, refers to the setting type.
 441                   *
 442                   * @since 4.1.0
 443                   *
 444                   * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
 445                   */
 446                  do_action( "customize_preview_{$this->type}", $this );
 447          }
 448  
 449          $this->is_previewed = true;
 450  
 451          return true;
 452      }
 453  
 454      /**
 455       * Clear out the previewed-applied flag for a multidimensional-aggregated value whenever its post value is updated.
 456       *
 457       * This ensures that the new value will get sanitized and used the next time
 458       * that `WP_Customize_Setting::_multidimensional_preview_filter()`
 459       * is called for this setting.
 460       *
 461       * @since 4.4.0
 462       *
 463       * @see WP_Customize_Manager::set_post_value()
 464       * @see WP_Customize_Setting::_multidimensional_preview_filter()
 465       */
 466      final public function _clear_aggregated_multidimensional_preview_applied_flag() {
 467          unset( self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['preview_applied_instances'][ $this->id ] );
 468      }
 469  
 470      /**
 471       * Suspends previewing the setting's option, so that its preview filters pass through the original value.
 472       *
 473       * This is done while the option is being sanitized or saved. Every call must be paired with a call to
 474       * {@see WP_Customize_Setting::resume_option_preview()}, including when an exception or error is thrown.
 475       *
 476       * @since 7.1.5
 477       */
 478  	private function suspend_option_preview() {
 479          /** @var string $id_base */
 480          $id_base = $this->id_data['base'];
 481  
 482          if ( ! isset( self::$suspended_option_previews[ $id_base ] ) ) {
 483              self::$suspended_option_previews[ $id_base ] = 1;
 484          } else {
 485              ++self::$suspended_option_previews[ $id_base ];
 486          }
 487      }
 488  
 489      /**
 490       * Resumes previewing the setting's option, once each suspension has been resumed.
 491       *
 492       * @since 7.1.5
 493       *
 494       * @see WP_Customize_Setting::suspend_option_preview()
 495       */
 496  	private function resume_option_preview() {
 497          /** @var string $id_base */
 498          $id_base = $this->id_data['base'];
 499  
 500          if ( ! isset( self::$suspended_option_previews[ $id_base ] ) ) {
 501              return;
 502          }
 503  
 504          if ( self::$suspended_option_previews[ $id_base ] > 1 ) {
 505              --self::$suspended_option_previews[ $id_base ];
 506          } else {
 507              unset( self::$suspended_option_previews[ $id_base ] );
 508          }
 509      }
 510  
 511      /**
 512       * Determines whether previewing the setting's option is suspended.
 513       *
 514       * @since 7.1.5
 515       *
 516       * @see WP_Customize_Setting::suspend_option_preview()
 517       *
 518       * @return bool Whether previewing the option is suspended.
 519       */
 520  	private function is_option_preview_suspended() {
 521          /** @var string $id_base */
 522          $id_base = $this->id_data['base'];
 523          return 'option' === $this->type && isset( self::$suspended_option_previews[ $id_base ] );
 524      }
 525  
 526      /**
 527       * Callback function to filter non-multidimensional theme mods and options.
 528       *
 529       * If switch_to_blog() was called after the preview() method, and the current
 530       * site is now not the same site, then this method does a no-op and returns
 531       * the original value.
 532       *
 533       * @since 3.4.0
 534       *
 535       * @param mixed $original Old value.
 536       * @return mixed New or old value.
 537       */
 538  	public function _preview_filter( $original ) {
 539          if ( ! $this->is_current_blog_previewed() || $this->is_option_preview_suspended() ) {
 540              return $original;
 541          }
 542  
 543          $undefined  = new stdClass(); // Symbol hack.
 544          $post_value = $this->post_value( $undefined );
 545          if ( $undefined !== $post_value ) {
 546              $value = $post_value;
 547          } else {
 548              /*
 549               * Note that we don't use $original here because preview() will
 550               * not add the filter in the first place if it has an initial value
 551               * and there is no post value.
 552               */
 553              $value = $this->default;
 554          }
 555          return $value;
 556      }
 557  
 558      /**
 559       * Callback function to filter multidimensional theme mods and options.
 560       *
 561       * For all multidimensional settings of a given type, the preview filter for
 562       * the first setting previewed will be used to apply the values for the others.
 563       *
 564       * @since 4.4.0
 565       *
 566       * @see WP_Customize_Setting::$aggregated_multidimensionals
 567       * @param mixed $original Original root value.
 568       * @return mixed New or old value.
 569       */
 570  	final public function _multidimensional_preview_filter( $original ) {
 571          if ( ! $this->is_current_blog_previewed() || $this->is_option_preview_suspended() ) {
 572              return $original;
 573          }
 574  
 575          $id_base = $this->id_data['base'];
 576  
 577          // If no settings have been previewed yet (which should not be the case, since $this is), just pass through the original value.
 578          if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) {
 579              return $original;
 580          }
 581  
 582          foreach ( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] as $previewed_setting ) {
 583              // Skip applying previewed value for any settings that have already been applied.
 584              if ( ! empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['preview_applied_instances'][ $previewed_setting->id ] ) ) {
 585                  continue;
 586              }
 587  
 588              // Do the replacements of the posted/default sub value into the root value.
 589              $value = $previewed_setting->post_value( $previewed_setting->default );
 590              $root  = self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value'];
 591              $root  = $previewed_setting->multidimensional_replace( $root, $previewed_setting->id_data['keys'], $value );
 592              self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value'] = $root;
 593  
 594              // Mark this setting having been applied so that it will be skipped when the filter is called again.
 595              self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['preview_applied_instances'][ $previewed_setting->id ] = true;
 596          }
 597  
 598          return self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
 599      }
 600  
 601      /**
 602       * Checks user capabilities and theme supports, and then saves
 603       * the value of the setting.
 604       *
 605       * @since 3.4.0
 606       *
 607       * @return void|false Void on success, false if cap check fails
 608       *                    or value isn't set or is invalid.
 609       */
 610  	final public function save() {
 611          /*
 612           * While saving an option setting, its preview filters pass through the persisted value. Otherwise,
 613           * update_option() would skip the update when the new value is the same as the previewed value, and
 614           * hooks which read the option while saving would get a value not sanitized with sanitize_option().
 615           */
 616          if ( 'option' === $this->type ) {
 617              $this->suspend_option_preview();
 618          }
 619  
 620          /*
 621           * Since a `finally` block requires PHP 5.5, the state is restored in each `catch` block before
 622           * rethrowing. Exceptions are caught for PHP 5, and errors such as TypeError for PHP 7+.
 623           */
 624          try {
 625              $this->is_saving = true;
 626              $value           = $this->post_value();
 627              $this->is_saving = false;
 628  
 629              if ( ! $this->check_capabilities() || ! isset( $value ) ) {
 630                  $this->end_saving();
 631                  return false;
 632              }
 633  
 634              /** @var string $id_base */
 635              $id_base = $this->id_data['base'];
 636  
 637              /**
 638               * Fires when the WP_Customize_Setting::save() method is called.
 639               *
 640               * The dynamic portion of the hook name, `$id_base` refers to
 641               * the base slug of the setting name.
 642               *
 643               * @since 3.4.0
 644               *
 645               * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
 646               */
 647              do_action( "customize_save_{$id_base}", $this );
 648  
 649              $this->update( $value );
 650          } catch ( Exception $e ) {
 651              $this->end_saving();
 652              throw $e;
 653          } catch ( Throwable $e ) {
 654              $this->end_saving();
 655              throw $e;
 656          }
 657  
 658          $this->end_saving();
 659      }
 660  
 661      /**
 662       * Restores the state changed while saving the setting.
 663       *
 664       * @since 7.1.5
 665       *
 666       * @see WP_Customize_Setting::save()
 667       */
 668  	private function end_saving() {
 669          $this->is_saving = false;
 670          if ( 'option' === $this->type ) {
 671              $this->resume_option_preview();
 672          }
 673      }
 674  
 675      /**
 676       * Fetch and sanitize the $_POST value for the setting.
 677       *
 678       * During a save request prior to save, post_value() provides the new value while value() does not.
 679       *
 680       * @since 3.4.0
 681       *
 682       * @param mixed $default_value A default value which is used as a fallback. Default null.
 683       * @return mixed The default value on failure, otherwise the sanitized and validated value.
 684       */
 685  	final public function post_value( $default_value = null ) {
 686          return $this->manager->post_value( $this, $default_value );
 687      }
 688  
 689      /**
 690       * Sanitize an input.
 691       *
 692       * @since 3.4.0
 693       * @since 7.1.5 The value of an option setting is additionally sanitized with `sanitize_option()`.
 694       *
 695       * @param string|array $value The value to sanitize.
 696       * @return string|array|null|WP_Error Sanitized value, or `null`/`WP_Error` if invalid.
 697       */
 698  	public function sanitize( $value ) {
 699          /**
 700           * Filters a Customize setting value in un-slashed form.
 701           *
 702           * @since 3.4.0
 703           *
 704           * @param mixed                $value   Value of the setting.
 705           * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
 706           */
 707          $value = apply_filters( "customize_sanitize_{$this->id}", $value, $this );
 708  
 709          /*
 710           * The value of an option setting is previewed via the option filters, bypassing the
 711           * sanitize_option() call in update_option(). So the value is sanitized here to ensure
 712           * that the previewed value is sanitized in the same way as the value which would be
 713           * persisted. When saving, this is skipped since update_option() sanitizes the value.
 714           */
 715          if ( 'option' === $this->type && ! $this->is_saving && ! is_null( $value ) && ! is_wp_error( $value ) ) {
 716              $value = $this->sanitize_option_value( $value );
 717          }
 718  
 719          return $value;
 720      }
 721  
 722      /**
 723       * Sanitizes the value of an option setting with `sanitize_option()`.
 724       *
 725       * This applies the sanitization for core options as well as for options sanitized via the
 726       * {@see 'sanitize_option_$option'} filter, such as by the `sanitize_callback` passed to
 727       * `register_setting()`. The value of a multidimensional setting is sanitized as part of
 728       * the root option value.
 729       *
 730       * Any errors added via `add_settings_error()` during sanitization are returned as a `WP_Error`.
 731       *
 732       * @since 7.1.5
 733       *
 734       * @global array<int, array{setting: string, code: string, message: string, type: string}>|null $wp_settings_errors Storage array of errors registered during this pageload.
 735       *
 736       * @param mixed $value Value which has already been sanitized by the setting's sanitize callback.
 737       * @return mixed|WP_Error Sanitized value, or `WP_Error` if invalid.
 738       */
 739  	private function sanitize_option_value( $value ) {
 740          global $wp_settings_errors;
 741  
 742          /** @var string $id_base */
 743          $id_base = $this->id_data['base'];
 744  
 745          /** @var string[] $keys */
 746          $keys = $this->id_data['keys'];
 747  
 748          // Callbacks for the "sanitize_option_{$option}" filter may call add_settings_error() without checking whether it exists.
 749          if ( ! function_exists( 'add_settings_error' ) ) {
 750              require_once  ABSPATH . 'wp-admin/includes/template.php';
 751          }
 752  
 753          if ( $this->is_multidimensional_aggregated ) {
 754              $root  = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
 755              $value = $this->multidimensional_replace( $root, $keys, $value );
 756          }
 757  
 758          // Capture only the errors added while sanitizing, and leave the existing errors untouched.
 759          $previous_settings_errors       = $wp_settings_errors;
 760          $previous_settings_errors_count = is_array( $wp_settings_errors ) ? count( $wp_settings_errors ) : 0;
 761  
 762          /*
 763           * While sanitizing, the preview filters for the option pass through the original value. This
 764           * prevents infinite recursion when sanitize_option() calls get_option() for the same option,
 765           * for example to fall back to the existing value when the value is invalid.
 766           *
 767           * Since a `finally` block requires PHP 5.5, the state is restored in each `catch` block before
 768           * rethrowing. Exceptions are caught for PHP 5, and errors such as TypeError for PHP 7+.
 769           */
 770          $this->suspend_option_preview();
 771          try {
 772              $value = sanitize_option( $id_base, $value );
 773          } catch ( Exception $e ) {
 774              $this->resume_option_preview();
 775              $wp_settings_errors = $previous_settings_errors;
 776              throw $e;
 777          } catch ( Throwable $e ) {
 778              $this->resume_option_preview();
 779              $wp_settings_errors = $previous_settings_errors;
 780              throw $e;
 781          }
 782          $this->resume_option_preview();
 783  
 784          $settings_errors    = is_array( $wp_settings_errors ) ? array_slice( $wp_settings_errors, $previous_settings_errors_count ) : array();
 785          $wp_settings_errors = $previous_settings_errors;
 786  
 787          $validity = new WP_Error();
 788          foreach ( $settings_errors as $settings_error ) {
 789              if ( 'error' === $settings_error['type'] ) {
 790                  $validity->add( $settings_error['code'], $settings_error['message'] );
 791              }
 792          }
 793          if ( array() !== $validity->get_error_codes() ) {
 794              return $validity;
 795          }
 796  
 797          if ( $this->is_multidimensional_aggregated ) {
 798              $value = $this->multidimensional_get( $value, $keys );
 799          }
 800  
 801          return $value;
 802      }
 803  
 804      /**
 805       * Validates an input.
 806       *
 807       * @since 4.6.0
 808       *
 809       * @see WP_REST_Request::has_valid_params()
 810       *
 811       * @param mixed $value Value to validate.
 812       * @return true|WP_Error True if the input was validated, otherwise WP_Error.
 813       */
 814  	public function validate( $value ) {
 815          if ( is_wp_error( $value ) ) {
 816              return $value;
 817          }
 818          if ( is_null( $value ) ) {
 819              return new WP_Error( 'invalid_value', __( 'Invalid value.' ) );
 820          }
 821  
 822          $validity = new WP_Error();
 823  
 824          /**
 825           * Validates a Customize setting value.
 826           *
 827           * Plugins should amend the `$validity` object via its `WP_Error::add()` method.
 828           *
 829           * The dynamic portion of the hook name, `$this->ID`, refers to the setting ID.
 830           *
 831           * @since 4.6.0
 832           *
 833           * @param WP_Error             $validity Filtered from `true` to `WP_Error` when invalid.
 834           * @param mixed                $value    Value of the setting.
 835           * @param WP_Customize_Setting $setting  WP_Customize_Setting instance.
 836           */
 837          $validity = apply_filters( "customize_validate_{$this->id}", $validity, $value, $this );
 838  
 839          if ( is_wp_error( $validity ) && ! $validity->has_errors() ) {
 840              $validity = true;
 841          }
 842          return $validity;
 843      }
 844  
 845      /**
 846       * Get the root value for a setting, especially for multidimensional ones.
 847       *
 848       * @since 4.4.0
 849       *
 850       * @param mixed $default_value Value to return if root does not exist.
 851       * @return mixed
 852       */
 853  	protected function get_root_value( $default_value = null ) {
 854          $id_base = $this->id_data['base'];
 855          if ( 'option' === $this->type ) {
 856              return get_option( $id_base, $default_value );
 857          } elseif ( 'theme_mod' === $this->type ) {
 858              return get_theme_mod( $id_base, $default_value );
 859          } else {
 860              /*
 861               * Any WP_Customize_Setting subclass implementing aggregate multidimensional
 862               * will need to override this method to obtain the data from the appropriate
 863               * location.
 864               */
 865              return $default_value;
 866          }
 867      }
 868  
 869      /**
 870       * Set the root value for a setting, especially for multidimensional ones.
 871       *
 872       * @since 4.4.0
 873       *
 874       * @param mixed $value Value to set as root of multidimensional setting.
 875       * @return bool Whether the multidimensional root was updated successfully.
 876       */
 877  	protected function set_root_value( $value ) {
 878          $id_base = $this->id_data['base'];
 879          if ( 'option' === $this->type ) {
 880              $autoload = true;
 881              if ( isset( self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload'] ) ) {
 882                  $autoload = self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload'];
 883              }
 884              return update_option( $id_base, $value, $autoload );
 885          } elseif ( 'theme_mod' === $this->type ) {
 886              set_theme_mod( $id_base, $value );
 887              return true;
 888          } else {
 889              /*
 890               * Any WP_Customize_Setting subclass implementing aggregate multidimensional
 891               * will need to override this method to obtain the data from the appropriate
 892               * location.
 893               */
 894              return false;
 895          }
 896      }
 897  
 898      /**
 899       * Save the value of the setting, using the related API.
 900       *
 901       * @since 3.4.0
 902       *
 903       * @param mixed $value The value to update.
 904       * @return bool The result of saving the value.
 905       */
 906  	protected function update( $value ) {
 907          $id_base = $this->id_data['base'];
 908          if ( 'option' === $this->type || 'theme_mod' === $this->type ) {
 909              if ( ! $this->is_multidimensional_aggregated ) {
 910                  return $this->set_root_value( $value );
 911              } else {
 912                  $root = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
 913                  $root = $this->multidimensional_replace( $root, $this->id_data['keys'], $value );
 914                  self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'] = $root;
 915                  return $this->set_root_value( $root );
 916              }
 917          } else {
 918              /**
 919               * Fires when the WP_Customize_Setting::update() method is called for settings
 920               * not handled as theme_mods or options.
 921               *
 922               * The dynamic portion of the hook name, `$this->type`, refers to the type of setting.
 923               *
 924               * @since 3.4.0
 925               *
 926               * @param mixed                $value   Value of the setting.
 927               * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
 928               */
 929              do_action( "customize_update_{$this->type}", $value, $this );
 930  
 931              return (bool) has_action( "customize_update_{$this->type}" );
 932          }
 933      }
 934  
 935      /**
 936       * Deprecated method.
 937       *
 938       * @since 3.4.0
 939       * @deprecated 4.4.0 Deprecated in favor of update() method.
 940       */
 941  	protected function _update_theme_mod() {
 942          _deprecated_function( __METHOD__, '4.4.0', __CLASS__ . '::update()' );
 943      }
 944  
 945      /**
 946       * Deprecated method.
 947       *
 948       * @since 3.4.0
 949       * @deprecated 4.4.0 Deprecated in favor of update() method.
 950       */
 951  	protected function _update_option() {
 952          _deprecated_function( __METHOD__, '4.4.0', __CLASS__ . '::update()' );
 953      }
 954  
 955      /**
 956       * Fetch the value of the setting.
 957       *
 958       * @since 3.4.0
 959       *
 960       * @return mixed The value.
 961       */
 962  	public function value() {
 963          $id_base      = $this->id_data['base'];
 964          $is_core_type = ( 'option' === $this->type || 'theme_mod' === $this->type );
 965  
 966          if ( ! $is_core_type && ! $this->is_multidimensional_aggregated ) {
 967  
 968              // Use post value if previewed and a post value is present.
 969              if ( $this->is_previewed ) {
 970                  $value = $this->post_value( null );
 971                  if ( null !== $value ) {
 972                      return $value;
 973                  }
 974              }
 975  
 976              $value = $this->get_root_value( $this->default );
 977  
 978              /**
 979               * Filters a Customize setting value not handled as a theme_mod or option.
 980               *
 981               * The dynamic portion of the hook name, `$id_base`, refers to
 982               * the base slug of the setting name, initialized from `$this->id_data['base']`.
 983               *
 984               * For settings handled as theme_mods or options, see those corresponding
 985               * functions for available hooks.
 986               *
 987               * @since 3.4.0
 988               * @since 4.6.0 Added the `$setting` instance as the second parameter.
 989               *
 990               * @param mixed                $default_value The setting default value. Default empty.
 991               * @param WP_Customize_Setting $setting       The setting instance.
 992               */
 993              $value = apply_filters( "customize_value_{$id_base}", $value, $this );
 994          } elseif ( $this->is_multidimensional_aggregated ) {
 995              $root_value = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
 996              $value      = $this->multidimensional_get( $root_value, $this->id_data['keys'], $this->default );
 997  
 998              // Ensure that the post value is used if the setting is previewed, since preview filters aren't applying on cached $root_value.
 999              if ( $this->is_previewed ) {
1000                  $value = $this->post_value( $value );
1001              }
1002          } else {
1003              $value = $this->get_root_value( $this->default );
1004          }
1005          return $value;
1006      }
1007  
1008      /**
1009       * Sanitize the setting's value for use in JavaScript.
1010       *
1011       * @since 3.4.0
1012       *
1013       * @return mixed The requested escaped value.
1014       */
1015  	public function js_value() {
1016  
1017          /**
1018           * Filters a Customize setting value for use in JavaScript.
1019           *
1020           * The dynamic portion of the hook name, `$this->id`, refers to the setting ID.
1021           *
1022           * @since 3.4.0
1023           *
1024           * @param mixed                $value   The setting value.
1025           * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
1026           */
1027          $value = apply_filters( "customize_sanitize_js_{$this->id}", $this->value(), $this );
1028  
1029          if ( is_string( $value ) ) {
1030              return html_entity_decode( $value, ENT_QUOTES, 'UTF-8' );
1031          }
1032  
1033          return $value;
1034      }
1035  
1036      /**
1037       * Retrieves the data to export to the client via JSON.
1038       *
1039       * @since 4.6.0
1040       *
1041       * @return array Array of parameters passed to JavaScript.
1042       */
1043  	public function json() {
1044          return array(
1045              'value'     => $this->js_value(),
1046              'transport' => $this->transport,
1047              'dirty'     => $this->dirty,
1048              'type'      => $this->type,
1049          );
1050      }
1051  
1052      /**
1053       * Validate user capabilities whether the theme supports the setting.
1054       *
1055       * @since 3.4.0
1056       *
1057       * @return bool False if theme doesn't support the setting or user can't change setting, otherwise true.
1058       */
1059  	final public function check_capabilities() {
1060          if ( $this->capability && ! current_user_can( $this->capability ) ) {
1061              return false;
1062          }
1063  
1064          if ( $this->theme_supports && ! current_theme_supports( ...(array) $this->theme_supports ) ) {
1065              return false;
1066          }
1067  
1068          return true;
1069      }
1070  
1071      /**
1072       * Multidimensional helper function.
1073       *
1074       * @since 3.4.0
1075       * @since 7.1.5 When creating, a non-array value is overridden with an array at every level, not only the last.
1076       *
1077       * @param array $root
1078       * @param array $keys
1079       * @param bool  $create Default false.
1080       * @return array|null Keys are 'root', 'node', and 'key'.
1081       */
1082  	final protected function multidimensional( &$root, $keys, $create = false ) {
1083          if ( $create && empty( $root ) ) {
1084              $root = array();
1085          }
1086  
1087          if ( ! isset( $root ) || empty( $keys ) ) {
1088              return null;
1089          }
1090  
1091          $last = array_pop( $keys );
1092          $node = &$root;
1093  
1094          foreach ( $keys as $key ) {
1095              if ( $create && ! is_array( $node ) ) {
1096                  // Account for an array overriding a string or object value.
1097                  $node = array();
1098              }
1099  
1100              if ( $create && ! isset( $node[ $key ] ) ) {
1101                  $node[ $key ] = array();
1102              }
1103  
1104              if ( ! is_array( $node ) || ! isset( $node[ $key ] ) ) {
1105                  return null;
1106              }
1107  
1108              $node = &$node[ $key ];
1109          }
1110  
1111          if ( $create ) {
1112              if ( ! is_array( $node ) ) {
1113                  // Account for an array overriding a string or object value.
1114                  $node = array();
1115              }
1116              $node[ $last ] ??= array();
1117          }
1118  
1119          if ( ! isset( $node[ $last ] ) ) {
1120              return null;
1121          }
1122  
1123          return array(
1124              'root' => &$root,
1125              'node' => &$node,
1126              'key'  => $last,
1127          );
1128      }
1129  
1130      /**
1131       * Will attempt to replace a specific value in a multidimensional array.
1132       *
1133       * @since 3.4.0
1134       *
1135       * @param array $root
1136       * @param array $keys
1137       * @param mixed $value The value to update.
1138       * @return mixed
1139       */
1140  	final protected function multidimensional_replace( $root, $keys, $value ) {
1141          if ( ! isset( $value ) ) {
1142              return $root;
1143          } elseif ( empty( $keys ) ) { // If there are no keys, we're replacing the root.
1144              return $value;
1145          }
1146  
1147          $result = $this->multidimensional( $root, $keys, true );
1148  
1149          if ( isset( $result ) ) {
1150              $result['node'][ $result['key'] ] = $value;
1151          }
1152  
1153          return $root;
1154      }
1155  
1156      /**
1157       * Will attempt to fetch a specific value from a multidimensional array.
1158       *
1159       * @since 3.4.0
1160       *
1161       * @param array $root
1162       * @param array $keys
1163       * @param mixed $default_value A default value which is used as a fallback. Default null.
1164       * @return mixed The requested value or the default value.
1165       */
1166  	final protected function multidimensional_get( $root, $keys, $default_value = null ) {
1167          if ( empty( $keys ) ) { // If there are no keys, test the root.
1168              return $root ?? $default_value;
1169          }
1170  
1171          $result = $this->multidimensional( $root, $keys );
1172          return isset( $result ) ? $result['node'][ $result['key'] ] : $default_value;
1173      }
1174  
1175      /**
1176       * Will attempt to check if a specific value in a multidimensional array is set.
1177       *
1178       * @since 3.4.0
1179       *
1180       * @param array $root
1181       * @param array $keys
1182       * @return bool True if value is set, false if not.
1183       */
1184  	final protected function multidimensional_isset( $root, $keys ) {
1185          $result = $this->multidimensional_get( $root, $keys );
1186          return isset( $result );
1187      }
1188  }
1189  
1190  /**
1191   * WP_Customize_Filter_Setting class.
1192   */
1193  require_once  ABSPATH . WPINC . '/customize/class-wp-customize-filter-setting.php';
1194  
1195  /**
1196   * WP_Customize_Header_Image_Setting class.
1197   */
1198  require_once  ABSPATH . WPINC . '/customize/class-wp-customize-header-image-setting.php';
1199  
1200  /**
1201   * WP_Customize_Background_Image_Setting class.
1202   */
1203  require_once  ABSPATH . WPINC . '/customize/class-wp-customize-background-image-setting.php';
1204  
1205  /**
1206   * WP_Customize_Nav_Menu_Item_Setting class.
1207   */
1208  require_once  ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-setting.php';
1209  
1210  /**
1211   * WP_Customize_Nav_Menu_Setting class.
1212   */
1213  require_once  ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-setting.php';


Generated : Tue Dec 1 08:20:01 2026 Cross-referenced by PHPXref