3 * WordPress Customize Setting classes
6 * @subpackage Customize
11 * Customize Setting class.
13 * Handles saving and sanitizing of settings.
17 * @see WP_Customize_Manager
19 class WP_Customize_Setting {
22 * @var WP_Customize_Manager
27 * Unique string identifier for the setting.
38 public $type = 'theme_mod';
41 * Capability required to edit this setting.
45 public $capability = 'edit_theme_options';
48 * Feature a theme is required to support to enable this setting.
53 public $theme_supports = '';
55 public $transport = 'refresh';
58 * Server-side sanitization callback for the setting's value.
62 public $validate_callback = '';
63 public $sanitize_callback = '';
64 public $sanitize_js_callback = '';
67 * Whether or not the setting is initially dirty when created.
69 * This is used to ensure that a setting will be sent from the pane to the
70 * preview when loading the Customizer. Normally a setting only is synced to
71 * the preview if it has been changed. This allows the setting to be sent
78 public $dirty = false;
83 protected $id_data = array();
86 * Whether or not preview() was called.
92 protected $is_previewed = false;
95 * Cache of multidimensional values to improve performance.
102 protected static $aggregated_multidimensionals = array();
105 * Whether the multidimensional setting is aggregated.
111 protected $is_multidimensional_aggregated = false;
116 * Any supplied $args override class property defaults.
120 * @param WP_Customize_Manager $manager
121 * @param string $id An specific ID of the setting. Can be a
122 * theme mod or option name.
123 * @param array $args Setting arguments.
125 public function __construct( $manager, $id, $args = array() ) {
126 $keys = array_keys( get_object_vars( $this ) );
127 foreach ( $keys as $key ) {
128 if ( isset( $args[ $key ] ) ) {
129 $this->$key = $args[ $key ];
133 $this->manager = $manager;
136 // Parse the ID for array keys.
137 $this->id_data['keys'] = preg_split( '/\[/', str_replace( ']', '', $this->id ) );
138 $this->id_data['base'] = array_shift( $this->id_data['keys'] );
141 $this->id = $this->id_data[ 'base' ];
142 if ( ! empty( $this->id_data[ 'keys' ] ) ) {
143 $this->id .= '[' . implode( '][', $this->id_data['keys'] ) . ']';
146 if ( $this->validate_callback ) {
147 add_filter( "customize_validate_{$this->id}", $this->validate_callback, 10, 3 );
149 if ( $this->sanitize_callback ) {
150 add_filter( "customize_sanitize_{$this->id}", $this->sanitize_callback, 10, 2 );
152 if ( $this->sanitize_js_callback ) {
153 add_filter( "customize_sanitize_js_{$this->id}", $this->sanitize_js_callback, 10, 2 );
156 if ( 'option' === $this->type || 'theme_mod' === $this->type ) {
157 // Other setting types can opt-in to aggregate multidimensional explicitly.
158 $this->aggregate_multidimensional();
160 // Allow option settings to indicate whether they should be autoloaded.
161 if ( 'option' === $this->type && isset( $args['autoload'] ) ) {
162 self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload'] = $args['autoload'];
168 * Get parsed ID data for multidimensional setting.
174 * ID data for multidimensional setting.
176 * @type string $base ID base
177 * @type array $keys Keys for multidimensional array.
180 final public function id_data() {
181 return $this->id_data;
185 * Set up the setting for aggregated multidimensional values.
187 * When a multidimensional setting gets aggregated, all of its preview and update
188 * calls get combined into one call, greatly improving performance.
193 protected function aggregate_multidimensional() {
194 $id_base = $this->id_data['base'];
195 if ( ! isset( self::$aggregated_multidimensionals[ $this->type ] ) ) {
196 self::$aggregated_multidimensionals[ $this->type ] = array();
198 if ( ! isset( self::$aggregated_multidimensionals[ $this->type ][ $id_base ] ) ) {
199 self::$aggregated_multidimensionals[ $this->type ][ $id_base ] = array(
200 'previewed_instances' => array(), // Calling preview() will add the $setting to the array.
201 'preview_applied_instances' => array(), // Flags for which settings have had their values applied.
202 'root_value' => $this->get_root_value( array() ), // Root value for initial state, manipulated by preview and update calls.
206 if ( ! empty( $this->id_data['keys'] ) ) {
207 // Note the preview-applied flag is cleared at priority 9 to ensure it is cleared before a deferred-preview runs.
208 add_action( "customize_post_value_set_{$this->id}", array( $this, '_clear_aggregated_multidimensional_preview_applied_flag' ), 9 );
209 $this->is_multidimensional_aggregated = true;
214 * Reset `$aggregated_multidimensionals` static variable.
216 * This is intended only for use by unit tests.
222 static public function reset_aggregated_multidimensionals() {
223 self::$aggregated_multidimensionals = array();
227 * The ID for the current site when the preview() method was called.
233 protected $_previewed_blog_id;
236 * Return true if the current site is not the same as the previewed site.
241 * @return bool If preview() has been called.
243 public function is_current_blog_previewed() {
244 if ( ! isset( $this->_previewed_blog_id ) ) {
247 return ( get_current_blog_id() === $this->_previewed_blog_id );
251 * Original non-previewed value stored by the preview method.
253 * @see WP_Customize_Setting::preview()
257 protected $_original_value;
260 * Add filters to supply the setting's value when accessed.
262 * If the setting already has a pre-existing value and there is no incoming
263 * post value for the setting, then this method will short-circuit since
264 * there is no change to preview.
267 * @since 4.4.0 Added boolean return value.
270 * @return bool False when preview short-circuits due no change needing to be previewed.
272 public function preview() {
273 if ( ! isset( $this->_previewed_blog_id ) ) {
274 $this->_previewed_blog_id = get_current_blog_id();
277 // Prevent re-previewing an already-previewed setting.
278 if ( $this->is_previewed ) {
282 $id_base = $this->id_data['base'];
283 $is_multidimensional = ! empty( $this->id_data['keys'] );
284 $multidimensional_filter = array( $this, '_multidimensional_preview_filter' );
287 * Check if the setting has a pre-existing value (an isset check),
288 * and if doesn't have any incoming post value. If both checks are true,
289 * then the preview short-circuits because there is nothing that needs
292 $undefined = new stdClass();
293 $needs_preview = ( $undefined !== $this->post_value( $undefined ) );
296 // Since no post value was defined, check if we have an initial value set.
297 if ( ! $needs_preview ) {
298 if ( $this->is_multidimensional_aggregated ) {
299 $root = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
300 $value = $this->multidimensional_get( $root, $this->id_data['keys'], $undefined );
302 $default = $this->default;
303 $this->default = $undefined; // Temporarily set default to undefined so we can detect if existing value is set.
304 $value = $this->value();
305 $this->default = $default;
307 $needs_preview = ( $undefined === $value ); // Because the default needs to be supplied.
310 // If the setting does not need previewing now, defer to when it has a value to preview.
311 if ( ! $needs_preview ) {
312 if ( ! has_action( "customize_post_value_set_{$this->id}", array( $this, 'preview' ) ) ) {
313 add_action( "customize_post_value_set_{$this->id}", array( $this, 'preview' ) );
318 switch ( $this->type ) {
320 if ( ! $is_multidimensional ) {
321 add_filter( "theme_mod_{$id_base}", array( $this, '_preview_filter' ) );
323 if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) {
324 // Only add this filter once for this ID base.
325 add_filter( "theme_mod_{$id_base}", $multidimensional_filter );
327 self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'][ $this->id ] = $this;
331 if ( ! $is_multidimensional ) {
332 add_filter( "pre_option_{$id_base}", array( $this, '_preview_filter' ) );
334 if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) {
335 // Only add these filters once for this ID base.
336 add_filter( "option_{$id_base}", $multidimensional_filter );
337 add_filter( "default_option_{$id_base}", $multidimensional_filter );
339 self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'][ $this->id ] = $this;
345 * Fires when the WP_Customize_Setting::preview() method is called for settings
346 * not handled as theme_mods or options.
348 * The dynamic portion of the hook name, `$this->id`, refers to the setting ID.
352 * @param WP_Customize_Setting $this WP_Customize_Setting instance.
354 do_action( "customize_preview_{$this->id}", $this );
357 * Fires when the WP_Customize_Setting::preview() method is called for settings
358 * not handled as theme_mods or options.
360 * The dynamic portion of the hook name, `$this->type`, refers to the setting type.
364 * @param WP_Customize_Setting $this WP_Customize_Setting instance.
366 do_action( "customize_preview_{$this->type}", $this );
369 $this->is_previewed = true;
375 * Clear out the previewed-applied flag for a multidimensional-aggregated value whenever its post value is updated.
377 * This ensures that the new value will get sanitized and used the next time
378 * that `WP_Customize_Setting::_multidimensional_preview_filter()`
379 * is called for this setting.
383 * @see WP_Customize_Manager::set_post_value()
384 * @see WP_Customize_Setting::_multidimensional_preview_filter()
386 final public function _clear_aggregated_multidimensional_preview_applied_flag() {
387 unset( self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['preview_applied_instances'][ $this->id ] );
391 * Callback function to filter non-multidimensional theme mods and options.
393 * If switch_to_blog() was called after the preview() method, and the current
394 * site is now not the same site, then this method does a no-op and returns
395 * the original value.
399 * @param mixed $original Old value.
400 * @return mixed New or old value.
402 public function _preview_filter( $original ) {
403 if ( ! $this->is_current_blog_previewed() ) {
407 $undefined = new stdClass(); // Symbol hack.
408 $post_value = $this->post_value( $undefined );
409 if ( $undefined !== $post_value ) {
410 $value = $post_value;
413 * Note that we don't use $original here because preview() will
414 * not add the filter in the first place if it has an initial value
415 * and there is no post value.
417 $value = $this->default;
423 * Callback function to filter multidimensional theme mods and options.
425 * For all multidimensional settings of a given type, the preview filter for
426 * the first setting previewed will be used to apply the values for the others.
431 * @see WP_Customize_Setting::$aggregated_multidimensionals
432 * @param mixed $original Original root value.
433 * @return mixed New or old value.
435 final public function _multidimensional_preview_filter( $original ) {
436 if ( ! $this->is_current_blog_previewed() ) {
440 $id_base = $this->id_data['base'];
442 // If no settings have been previewed yet (which should not be the case, since $this is), just pass through the original value.
443 if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) {
447 foreach ( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] as $previewed_setting ) {
448 // Skip applying previewed value for any settings that have already been applied.
449 if ( ! empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['preview_applied_instances'][ $previewed_setting->id ] ) ) {
453 // Do the replacements of the posted/default sub value into the root value.
454 $value = $previewed_setting->post_value( $previewed_setting->default );
455 $root = self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value'];
456 $root = $previewed_setting->multidimensional_replace( $root, $previewed_setting->id_data['keys'], $value );
457 self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value'] = $root;
459 // Mark this setting having been applied so that it will be skipped when the filter is called again.
460 self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['preview_applied_instances'][ $previewed_setting->id ] = true;
463 return self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
467 * Checks user capabilities and theme supports, and then saves
468 * the value of the setting.
474 * @return false|void False if cap check fails or value isn't set or is invalid.
476 final public function save() {
477 $value = $this->post_value();
479 if ( ! $this->check_capabilities() || ! isset( $value ) ) {
484 * Fires when the WP_Customize_Setting::save() method is called.
486 * The dynamic portion of the hook name, `$this->id_data['base']` refers to
487 * the base slug of the setting name.
491 * @param WP_Customize_Setting $this WP_Customize_Setting instance.
493 do_action( 'customize_save_' . $this->id_data['base'], $this );
495 $this->update( $value );
499 * Fetch and sanitize the $_POST value for the setting.
501 * During a save request prior to save, post_value() provides the new value while value() does not.
505 * @param mixed $default A default value which is used as a fallback. Default is null.
506 * @return mixed The default value on failure, otherwise the sanitized and validated value.
508 final public function post_value( $default = null ) {
509 return $this->manager->post_value( $this, $default );
517 * @param string|array $value The value to sanitize.
518 * @return string|array|null|WP_Error Sanitized value, or `null`/`WP_Error` if invalid.
520 public function sanitize( $value ) {
523 * Filters a Customize setting value in un-slashed form.
527 * @param mixed $value Value of the setting.
528 * @param WP_Customize_Setting $this WP_Customize_Setting instance.
530 return apply_filters( "customize_sanitize_{$this->id}", $value, $this );
534 * Validates an input.
539 * @see WP_REST_Request::has_valid_params()
541 * @param mixed $value Value to validate.
542 * @return true|WP_Error True if the input was validated, otherwise WP_Error.
544 public function validate( $value ) {
545 if ( is_wp_error( $value ) ) {
548 if ( is_null( $value ) ) {
549 return new WP_Error( 'invalid_value', __( 'Invalid value.' ) );
552 $validity = new WP_Error();
555 * Validates a Customize setting value.
557 * Plugins should amend the `$validity` object via its `WP_Error::add()` method.
559 * The dynamic portion of the hook name, `$this->ID`, refers to the setting ID.
563 * @param WP_Error $validity Filtered from `true` to `WP_Error` when invalid.
564 * @param mixed $value Value of the setting.
565 * @param WP_Customize_Setting $this WP_Customize_Setting instance.
567 $validity = apply_filters( "customize_validate_{$this->id}", $validity, $value, $this );
569 if ( is_wp_error( $validity ) && empty( $validity->errors ) ) {
576 * Get the root value for a setting, especially for multidimensional ones.
581 * @param mixed $default Value to return if root does not exist.
584 protected function get_root_value( $default = null ) {
585 $id_base = $this->id_data['base'];
586 if ( 'option' === $this->type ) {
587 return get_option( $id_base, $default );
588 } else if ( 'theme_mod' ) {
589 return get_theme_mod( $id_base, $default );
592 * Any WP_Customize_Setting subclass implementing aggregate multidimensional
593 * will need to override this method to obtain the data from the appropriate
601 * Set the root value for a setting, especially for multidimensional ones.
606 * @param mixed $value Value to set as root of multidimensional setting.
607 * @return bool Whether the multidimensional root was updated successfully.
609 protected function set_root_value( $value ) {
610 $id_base = $this->id_data['base'];
611 if ( 'option' === $this->type ) {
613 if ( isset( self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload'] ) ) {
614 $autoload = self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload'];
616 return update_option( $id_base, $value, $autoload );
617 } else if ( 'theme_mod' ) {
618 set_theme_mod( $id_base, $value );
622 * Any WP_Customize_Setting subclass implementing aggregate multidimensional
623 * will need to override this method to obtain the data from the appropriate
631 * Save the value of the setting, using the related API.
635 * @param mixed $value The value to update.
636 * @return bool The result of saving the value.
638 protected function update( $value ) {
639 $id_base = $this->id_data['base'];
640 if ( 'option' === $this->type || 'theme_mod' === $this->type ) {
641 if ( ! $this->is_multidimensional_aggregated ) {
642 return $this->set_root_value( $value );
644 $root = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
645 $root = $this->multidimensional_replace( $root, $this->id_data['keys'], $value );
646 self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'] = $root;
647 return $this->set_root_value( $root );
651 * Fires when the WP_Customize_Setting::update() method is called for settings
652 * not handled as theme_mods or options.
654 * The dynamic portion of the hook name, `$this->type`, refers to the type of setting.
658 * @param mixed $value Value of the setting.
659 * @param WP_Customize_Setting $this WP_Customize_Setting instance.
661 do_action( "customize_update_{$this->type}", $value, $this );
663 return has_action( "customize_update_{$this->type}" );
671 * @deprecated 4.4.0 Deprecated in favor of update() method.
673 protected function _update_theme_mod() {
674 _deprecated_function( __METHOD__, '4.4.0', __CLASS__ . '::update()' );
681 * @deprecated 4.4.0 Deprecated in favor of update() method.
683 protected function _update_option() {
684 _deprecated_function( __METHOD__, '4.4.0', __CLASS__ . '::update()' );
688 * Fetch the value of the setting.
692 * @return mixed The value.
694 public function value() {
695 $id_base = $this->id_data['base'];
696 $is_core_type = ( 'option' === $this->type || 'theme_mod' === $this->type );
698 if ( ! $is_core_type && ! $this->is_multidimensional_aggregated ) {
700 // Use post value if previewed and a post value is present.
701 if ( $this->is_previewed ) {
702 $value = $this->post_value( null );
703 if ( null !== $value ) {
708 $value = $this->get_root_value( $this->default );
711 * Filters a Customize setting value not handled as a theme_mod or option.
713 * The dynamic portion of the hook name, `$id_base`, refers to
714 * the base slug of the setting name, initialized from `$this->id_data['base']`.
716 * For settings handled as theme_mods or options, see those corresponding
717 * functions for available hooks.
720 * @since 4.6.0 Added the `$this` setting instance as the second parameter.
722 * @param mixed $default The setting default value. Default empty.
723 * @param WP_Customize_Setting $this The setting instance.
725 $value = apply_filters( "customize_value_{$id_base}", $value, $this );
726 } elseif ( $this->is_multidimensional_aggregated ) {
727 $root_value = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'];
728 $value = $this->multidimensional_get( $root_value, $this->id_data['keys'], $this->default );
730 // Ensure that the post value is used if the setting is previewed, since preview filters aren't applying on cached $root_value.
731 if ( $this->is_previewed ) {
732 $value = $this->post_value( $value );
735 $value = $this->get_root_value( $this->default );
741 * Sanitize the setting's value for use in JavaScript.
745 * @return mixed The requested escaped value.
747 public function js_value() {
750 * Filters a Customize setting value for use in JavaScript.
752 * The dynamic portion of the hook name, `$this->id`, refers to the setting ID.
756 * @param mixed $value The setting value.
757 * @param WP_Customize_Setting $this WP_Customize_Setting instance.
759 $value = apply_filters( "customize_sanitize_js_{$this->id}", $this->value(), $this );
761 if ( is_string( $value ) )
762 return html_entity_decode( $value, ENT_QUOTES, 'UTF-8');
768 * Retrieves the data to export to the client via JSON.
773 * @return array Array of parameters passed to JavaScript.
775 public function json() {
777 'value' => $this->js_value(),
778 'transport' => $this->transport,
779 'dirty' => $this->dirty,
780 'type' => $this->type,
785 * Validate user capabilities whether the theme supports the setting.
789 * @return bool False if theme doesn't support the setting or user can't change setting, otherwise true.
791 final public function check_capabilities() {
792 if ( $this->capability && ! call_user_func_array( 'current_user_can', (array) $this->capability ) )
795 if ( $this->theme_supports && ! call_user_func_array( 'current_theme_supports', (array) $this->theme_supports ) )
802 * Multidimensional helper function.
808 * @param bool $create Default is false.
809 * @return array|void Keys are 'root', 'node', and 'key'.
811 final protected function multidimensional( &$root, $keys, $create = false ) {
812 if ( $create && empty( $root ) )
815 if ( ! isset( $root ) || empty( $keys ) )
818 $last = array_pop( $keys );
821 foreach ( $keys as $key ) {
822 if ( $create && ! isset( $node[ $key ] ) )
823 $node[ $key ] = array();
825 if ( ! is_array( $node ) || ! isset( $node[ $key ] ) )
828 $node = &$node[ $key ];
832 if ( ! is_array( $node ) ) {
833 // account for an array overriding a string or object value
836 if ( ! isset( $node[ $last ] ) ) {
837 $node[ $last ] = array();
841 if ( ! isset( $node[ $last ] ) )
852 * Will attempt to replace a specific value in a multidimensional array.
858 * @param mixed $value The value to update.
861 final protected function multidimensional_replace( $root, $keys, $value ) {
862 if ( ! isset( $value ) )
864 elseif ( empty( $keys ) ) // If there are no keys, we're replacing the root.
867 $result = $this->multidimensional( $root, $keys, true );
869 if ( isset( $result ) )
870 $result['node'][ $result['key'] ] = $value;
876 * Will attempt to fetch a specific value from a multidimensional array.
882 * @param mixed $default A default value which is used as a fallback. Default is null.
883 * @return mixed The requested value or the default value.
885 final protected function multidimensional_get( $root, $keys, $default = null ) {
886 if ( empty( $keys ) ) // If there are no keys, test the root.
887 return isset( $root ) ? $root : $default;
889 $result = $this->multidimensional( $root, $keys );
890 return isset( $result ) ? $result['node'][ $result['key'] ] : $default;
894 * Will attempt to check if a specific value in a multidimensional array is set.
900 * @return bool True if value is set, false if not.
902 final protected function multidimensional_isset( $root, $keys ) {
903 $result = $this->multidimensional_get( $root, $keys );
904 return isset( $result );
908 /** WP_Customize_Filter_Setting class */
909 require_once( ABSPATH . WPINC . '/customize/class-wp-customize-filter-setting.php' );
911 /** WP_Customize_Header_Image_Setting class */
912 require_once( ABSPATH . WPINC . '/customize/class-wp-customize-header-image-setting.php' );
914 /** WP_Customize_Background_Image_Setting class */
915 require_once( ABSPATH . WPINC . '/customize/class-wp-customize-background-image-setting.php' );
917 /** WP_Customize_Nav_Menu_Item_Setting class */
918 require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-setting.php' );
920 /** WP_Customize_Nav_Menu_Setting class */
921 require_once( ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-setting.php' );