3 * WordPress Customize Widgets classes
6 * @subpackage Customize
11 * Customize Widgets class.
13 * Implements widget management in the Customizer.
17 * @see WP_Customize_Manager
19 final class WP_Customize_Widgets {
22 * WP_Customize_Manager instance.
26 * @var WP_Customize_Manager
31 * All id_bases for widgets defined in core.
37 protected $core_widget_id_bases = array(
38 'archives', 'calendar', 'categories', 'links', 'meta',
39 'nav_menu', 'pages', 'recent-comments', 'recent-posts',
40 'rss', 'search', 'tag_cloud', 'text',
48 protected $rendered_sidebars = array();
55 protected $rendered_widgets = array();
62 protected $old_sidebars_widgets = array();
65 * Mapping of widget ID base to whether it supports selective refresh.
71 protected $selective_refreshable_widgets;
74 * Mapping of setting type to setting ID pattern.
80 protected $setting_id_patterns = array(
81 'widget_instance' => '/^widget_(?P<id_base>.+?)(?:\[(?P<widget_number>\d+)\])?$/',
82 'sidebar_widgets' => '/^sidebars_widgets\[(?P<sidebar_id>.+?)\]$/',
91 * @param WP_Customize_Manager $manager Customize manager bootstrap instance.
93 public function __construct( $manager ) {
94 $this->manager = $manager;
96 // Skip useless hooks when the user can't manage widgets anyway.
97 if ( ! current_user_can( 'edit_theme_options' ) ) {
101 add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
102 add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
103 add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
104 add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
105 add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
106 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
107 add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
108 add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
109 add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
110 add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
111 add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
112 add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
114 add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
115 add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
116 add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
118 // Selective Refresh.
119 add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
120 add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
124 * List whether each registered widget can be use selective refresh.
126 * If the theme does not support the customize-selective-refresh-widgets feature,
127 * then this will always return an empty array.
132 * @return array Mapping of id_base to support. If theme doesn't support
133 * selective refresh, an empty array is returned.
135 public function get_selective_refreshable_widgets() {
136 global $wp_widget_factory;
137 if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
140 if ( ! isset( $this->selective_refreshable_widgets ) ) {
141 $this->selective_refreshable_widgets = array();
142 foreach ( $wp_widget_factory->widgets as $wp_widget ) {
143 $this->selective_refreshable_widgets[ $wp_widget->id_base ] = ! empty( $wp_widget->widget_options['customize_selective_refresh'] );
146 return $this->selective_refreshable_widgets;
150 * Determines if a widget supports selective refresh.
155 * @param string $id_base Widget ID Base.
156 * @return bool Whether the widget can be selective refreshed.
158 public function is_widget_selective_refreshable( $id_base ) {
159 $selective_refreshable_widgets = $this->get_selective_refreshable_widgets();
160 return ! empty( $selective_refreshable_widgets[ $id_base ] );
164 * Retrieves the widget setting type given a setting ID.
169 * @staticvar array $cache
171 * @param string $setting_id Setting ID.
172 * @return string|void Setting type.
174 protected function get_setting_type( $setting_id ) {
175 static $cache = array();
176 if ( isset( $cache[ $setting_id ] ) ) {
177 return $cache[ $setting_id ];
179 foreach ( $this->setting_id_patterns as $type => $pattern ) {
180 if ( preg_match( $pattern, $setting_id ) ) {
181 $cache[ $setting_id ] = $type;
188 * Inspects the incoming customized data for any widget settings, and dynamically adds
189 * them up-front so widgets will be initialized properly.
194 public function register_settings() {
195 $widget_setting_ids = array();
196 $incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
197 foreach ( $incoming_setting_ids as $setting_id ) {
198 if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
199 $widget_setting_ids[] = $setting_id;
202 if ( $this->manager->doing_ajax( 'update-widget' ) && isset( $_REQUEST['widget-id'] ) ) {
203 $widget_setting_ids[] = $this->get_setting_id( wp_unslash( $_REQUEST['widget-id'] ) );
206 $settings = $this->manager->add_dynamic_settings( array_unique( $widget_setting_ids ) );
209 * Preview settings right away so that widgets and sidebars will get registered properly.
210 * But don't do this if a customize_save because this will cause WP to think there is nothing
211 * changed that needs to be saved.
213 if ( ! $this->manager->doing_ajax( 'customize_save' ) ) {
214 foreach ( $settings as $setting ) {
221 * Determines the arguments for a dynamically-created setting.
226 * @param false|array $args The arguments to the WP_Customize_Setting constructor.
227 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
228 * @return false|array Setting arguments, false otherwise.
230 public function filter_customize_dynamic_setting_args( $args, $setting_id ) {
231 if ( $this->get_setting_type( $setting_id ) ) {
232 $args = $this->get_setting_args( $setting_id );
238 * Retrieves an unslashed post value or return a default.
243 * @param string $name Post value.
244 * @param mixed $default Default post value.
245 * @return mixed Unslashed post value or default value.
247 protected function get_post_value( $name, $default = null ) {
248 if ( ! isset( $_POST[ $name ] ) ) {
252 return wp_unslash( $_POST[ $name ] );
256 * Override sidebars_widgets for theme switch.
258 * When switching a theme via the Customizer, supply any previously-configured
259 * sidebars_widgets from the target theme as the initial sidebars_widgets
260 * setting. Also store the old theme's existing settings so that they can
261 * be passed along for storing in the sidebars_widgets theme_mod when the
262 * theme gets switched.
267 * @global array $sidebars_widgets
268 * @global array $_wp_sidebars_widgets
270 public function override_sidebars_widgets_for_theme_switch() {
271 global $sidebars_widgets;
273 if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
277 $this->old_sidebars_widgets = wp_get_sidebars_widgets();
278 add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
280 // retrieve_widgets() looks at the global $sidebars_widgets
281 $sidebars_widgets = $this->old_sidebars_widgets;
282 $sidebars_widgets = retrieve_widgets( 'customize' );
283 add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
284 // reset global cache var used by wp_get_sidebars_widgets()
285 unset( $GLOBALS['_wp_sidebars_widgets'] );
289 * Filters old_sidebars_widgets_data Customizer setting.
291 * When switching themes, filter the Customizer setting old_sidebars_widgets_data
292 * to supply initial $sidebars_widgets before they were overridden by retrieve_widgets().
293 * The value for old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
299 * @see WP_Customize_Widgets::handle_theme_switch()
301 * @param array $old_sidebars_widgets
304 public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
305 return $this->old_sidebars_widgets;
309 * Filters sidebars_widgets option for theme switch.
311 * When switching themes, the retrieve_widgets() function is run when the Customizer initializes,
312 * and then the new sidebars_widgets here get supplied as the default value for the sidebars_widgets
318 * @see WP_Customize_Widgets::handle_theme_switch()
319 * @global array $sidebars_widgets
321 * @param array $sidebars_widgets
324 public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
325 $sidebars_widgets = $GLOBALS['sidebars_widgets'];
326 $sidebars_widgets['array_version'] = 3;
327 return $sidebars_widgets;
331 * Ensures all widgets get loaded into the Customizer.
333 * Note: these actions are also fired in wp_ajax_update_widget().
338 public function customize_controls_init() {
339 /** This action is documented in wp-admin/includes/ajax-actions.php */
340 do_action( 'load-widgets.php' );
342 /** This action is documented in wp-admin/includes/ajax-actions.php */
343 do_action( 'widgets.php' );
345 /** This action is documented in wp-admin/widgets.php */
346 do_action( 'sidebar_admin_setup' );
350 * Ensures widgets are available for all types of previews.
352 * When in preview, hook to {@see 'customize_register'} for settings after WordPress is loaded
353 * so that all filters have been initialized (e.g. Widget Visibility).
358 public function schedule_customize_register() {
360 $this->customize_register();
362 add_action( 'wp', array( $this, 'customize_register' ) );
367 * Registers Customizer settings and controls for all sidebars and widgets.
372 * @global array $wp_registered_widgets
373 * @global array $wp_registered_widget_controls
374 * @global array $wp_registered_sidebars
376 public function customize_register() {
377 global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
379 add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
381 $sidebars_widgets = array_merge(
382 array( 'wp_inactive_widgets' => array() ),
383 array_fill_keys( array_keys( $wp_registered_sidebars ), array() ),
384 wp_get_sidebars_widgets()
387 $new_setting_ids = array();
390 * Register a setting for all widgets, including those which are active,
391 * inactive, and orphaned since a widget may get suppressed from a sidebar
392 * via a plugin (like Widget Visibility).
394 foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
395 $setting_id = $this->get_setting_id( $widget_id );
396 $setting_args = $this->get_setting_args( $setting_id );
397 if ( ! $this->manager->get_setting( $setting_id ) ) {
398 $this->manager->add_setting( $setting_id, $setting_args );
400 $new_setting_ids[] = $setting_id;
404 * Add a setting which will be supplied for the theme's sidebars_widgets
405 * theme_mod when the theme is switched.
407 if ( ! $this->manager->is_theme_active() ) {
408 $setting_id = 'old_sidebars_widgets_data';
409 $setting_args = $this->get_setting_args( $setting_id, array(
410 'type' => 'global_variable',
413 $this->manager->add_setting( $setting_id, $setting_args );
416 $this->manager->add_panel( 'widgets', array(
418 'title' => __( 'Widgets' ),
419 'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
421 'active_callback' => array( $this, 'is_panel_active' ),
424 foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
425 if ( empty( $sidebar_widget_ids ) ) {
426 $sidebar_widget_ids = array();
429 $is_registered_sidebar = is_registered_sidebar( $sidebar_id );
430 $is_inactive_widgets = ( 'wp_inactive_widgets' === $sidebar_id );
431 $is_active_sidebar = ( $is_registered_sidebar && ! $is_inactive_widgets );
433 // Add setting for managing the sidebar's widgets.
434 if ( $is_registered_sidebar || $is_inactive_widgets ) {
435 $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
436 $setting_args = $this->get_setting_args( $setting_id );
437 if ( ! $this->manager->get_setting( $setting_id ) ) {
438 if ( ! $this->manager->is_theme_active() ) {
439 $setting_args['dirty'] = true;
441 $this->manager->add_setting( $setting_id, $setting_args );
443 $new_setting_ids[] = $setting_id;
445 // Add section to contain controls.
446 $section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
447 if ( $is_active_sidebar ) {
449 $section_args = array(
450 'title' => $wp_registered_sidebars[ $sidebar_id ]['name'],
451 'description' => $wp_registered_sidebars[ $sidebar_id ]['description'],
452 'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ) ),
453 'panel' => 'widgets',
454 'sidebar_id' => $sidebar_id,
458 * Filters Customizer widget section arguments for a given sidebar.
462 * @param array $section_args Array of Customizer widget section arguments.
463 * @param string $section_id Customizer section ID.
464 * @param int|string $sidebar_id Sidebar ID.
466 $section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
468 $section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
469 $this->manager->add_section( $section );
471 $control = new WP_Widget_Area_Customize_Control( $this->manager, $setting_id, array(
472 'section' => $section_id,
473 'sidebar_id' => $sidebar_id,
474 'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
476 $new_setting_ids[] = $setting_id;
478 $this->manager->add_control( $control );
482 // Add a control for each active widget (located in a sidebar).
483 foreach ( $sidebar_widget_ids as $i => $widget_id ) {
485 // Skip widgets that may have gone away due to a plugin being deactivated.
486 if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[$widget_id] ) ) {
490 $registered_widget = $wp_registered_widgets[$widget_id];
491 $setting_id = $this->get_setting_id( $widget_id );
492 $id_base = $wp_registered_widget_controls[$widget_id]['id_base'];
494 $control = new WP_Widget_Form_Customize_Control( $this->manager, $setting_id, array(
495 'label' => $registered_widget['name'],
496 'section' => $section_id,
497 'sidebar_id' => $sidebar_id,
498 'widget_id' => $widget_id,
499 'widget_id_base' => $id_base,
501 'width' => $wp_registered_widget_controls[$widget_id]['width'],
502 'height' => $wp_registered_widget_controls[$widget_id]['height'],
503 'is_wide' => $this->is_wide_widget( $widget_id ),
505 $this->manager->add_control( $control );
509 if ( ! $this->manager->doing_ajax( 'customize_save' ) ) {
510 foreach ( $new_setting_ids as $new_setting_id ) {
511 $this->manager->get_setting( $new_setting_id )->preview();
517 * Determines whether the widgets panel is active, based on whether there are sidebars registered.
522 * @see WP_Customize_Panel::$active_callback
524 * @global array $wp_registered_sidebars
525 * @return bool Active.
527 public function is_panel_active() {
528 global $wp_registered_sidebars;
529 return ! empty( $wp_registered_sidebars );
533 * Converts a widget_id into its corresponding Customizer setting ID (option name).
538 * @param string $widget_id Widget ID.
539 * @return string Maybe-parsed widget ID.
541 public function get_setting_id( $widget_id ) {
542 $parsed_widget_id = $this->parse_widget_id( $widget_id );
543 $setting_id = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
545 if ( ! is_null( $parsed_widget_id['number'] ) ) {
546 $setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
552 * Determines whether the widget is considered "wide".
554 * Core widgets which may have controls wider than 250, but can still be shown
555 * in the narrow Customizer panel. The RSS and Text widgets in Core, for example,
556 * have widths of 400 and yet they still render fine in the Customizer panel.
558 * This method will return all Core widgets as being not wide, but this can be
559 * overridden with the {@see 'is_wide_widget_in_customizer'} filter.
564 * @global $wp_registered_widget_controls
566 * @param string $widget_id Widget ID.
567 * @return bool Whether or not the widget is a "wide" widget.
569 public function is_wide_widget( $widget_id ) {
570 global $wp_registered_widget_controls;
572 $parsed_widget_id = $this->parse_widget_id( $widget_id );
573 $width = $wp_registered_widget_controls[$widget_id]['width'];
574 $is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases );
575 $is_wide = ( $width > 250 && ! $is_core );
578 * Filters whether the given widget is considered "wide".
582 * @param bool $is_wide Whether the widget is wide, Default false.
583 * @param string $widget_id Widget ID.
585 return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
589 * Converts a widget ID into its id_base and number components.
594 * @param string $widget_id Widget ID.
595 * @return array Array containing a widget's id_base and number components.
597 public function parse_widget_id( $widget_id ) {
603 if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
604 $parsed['id_base'] = $matches[1];
605 $parsed['number'] = intval( $matches[2] );
607 // likely an old single widget
608 $parsed['id_base'] = $widget_id;
614 * Converts a widget setting ID (option path) to its id_base and number components.
619 * @param string $setting_id Widget setting ID.
620 * @return WP_Error|array Array containing a widget's id_base and number components,
621 * or a WP_Error object.
623 public function parse_widget_setting_id( $setting_id ) {
624 if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
625 return new WP_Error( 'widget_setting_invalid_id' );
628 $id_base = $matches[2];
629 $number = isset( $matches[3] ) ? intval( $matches[3] ) : null;
631 return compact( 'id_base', 'number' );
635 * Calls admin_print_styles-widgets.php and admin_print_styles hooks to
636 * allow custom styles from plugins.
641 public function print_styles() {
642 /** This action is documented in wp-admin/admin-header.php */
643 do_action( 'admin_print_styles-widgets.php' );
645 /** This action is documented in wp-admin/admin-header.php */
646 do_action( 'admin_print_styles' );
650 * Calls admin_print_scripts-widgets.php and admin_print_scripts hooks to
651 * allow custom scripts from plugins.
656 public function print_scripts() {
657 /** This action is documented in wp-admin/admin-header.php */
658 do_action( 'admin_print_scripts-widgets.php' );
660 /** This action is documented in wp-admin/admin-header.php */
661 do_action( 'admin_print_scripts' );
665 * Enqueues scripts and styles for Customizer panel and export data to JavaScript.
670 * @global WP_Scripts $wp_scripts
671 * @global array $wp_registered_sidebars
672 * @global array $wp_registered_widgets
674 public function enqueue_scripts() {
675 global $wp_scripts, $wp_registered_sidebars, $wp_registered_widgets;
677 wp_enqueue_style( 'customize-widgets' );
678 wp_enqueue_script( 'customize-widgets' );
680 /** This action is documented in wp-admin/admin-header.php */
681 do_action( 'admin_enqueue_scripts', 'widgets.php' );
684 * Export available widgets with control_tpl removed from model
685 * since plugins need templates to be in the DOM.
687 $available_widgets = array();
689 foreach ( $this->get_available_widgets() as $available_widget ) {
690 unset( $available_widget['control_tpl'] );
691 $available_widgets[] = $available_widget;
694 $widget_reorder_nav_tpl = sprintf(
695 '<div class="widget-reorder-nav"><span class="move-widget" tabindex="0">%1$s</span><span class="move-widget-down" tabindex="0">%2$s</span><span class="move-widget-up" tabindex="0">%3$s</span></div>',
696 __( 'Move to another area…' ),
701 $move_widget_area_tpl = str_replace(
702 array( '{description}', '{btn}' ),
704 __( 'Select an area to move this widget into:' ),
705 _x( 'Move', 'Move widget' ),
707 '<div class="move-widget-area">
708 <p class="description">{description}</p>
709 <ul class="widget-area-select">
710 <% _.each( sidebars, function ( sidebar ){ %>
711 <li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
714 <div class="move-widget-actions">
715 <button class="move-widget-btn button-secondary" type="button">{btn}</button>
721 'registeredSidebars' => array_values( $wp_registered_sidebars ),
722 'registeredWidgets' => $wp_registered_widgets,
723 'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets
725 'saveBtnLabel' => __( 'Apply' ),
726 'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
727 'removeBtnLabel' => __( 'Remove' ),
728 'removeBtnTooltip' => __( 'Trash widget by moving it to the inactive widgets sidebar.' ),
729 'error' => __( 'An error has occurred. Please reload the page and try again.' ),
730 'widgetMovedUp' => __( 'Widget moved up' ),
731 'widgetMovedDown' => __( 'Widget moved down' ),
732 'noAreasRendered' => __( 'There are no widget areas currently rendered in the preview. Navigate in the preview to a template that makes use of a widget area in order to access its widgets here.' ),
733 'reorderModeOn' => __( 'Reorder mode enabled' ),
734 'reorderModeOff' => __( 'Reorder mode closed' ),
735 'reorderLabelOn' => esc_attr__( 'Reorder widgets' ),
736 'reorderLabelOff' => esc_attr__( 'Close reorder mode' ),
739 'widgetReorderNav' => $widget_reorder_nav_tpl,
740 'moveWidgetArea' => $move_widget_area_tpl,
742 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
745 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
746 unset( $registered_widget['callback'] ); // may not be JSON-serializeable
749 $wp_scripts->add_data(
752 sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
757 * Renders the widget form control templates into the DOM.
762 public function output_widget_control_templates() {
764 <div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
765 <div id="available-widgets">
766 <div class="customize-section-title">
767 <button class="customize-section-back" tabindex="-1">
768 <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
771 <span class="customize-action"><?php
772 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
773 echo sprintf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'widgets' )->title ) );
775 <?php _e( 'Add a Widget' ); ?>
778 <div id="available-widgets-filter">
779 <label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
780 <input type="search" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets…' ) ?>" />
782 <div id="available-widgets-list">
783 <?php foreach ( $this->get_available_widgets() as $available_widget ): ?>
784 <div id="widget-tpl-<?php echo esc_attr( $available_widget['id'] ) ?>" data-widget-id="<?php echo esc_attr( $available_widget['id'] ) ?>" class="widget-tpl <?php echo esc_attr( $available_widget['id'] ) ?>" tabindex="0">
785 <?php echo $available_widget['control_tpl']; ?>
788 </div><!-- #available-widgets-list -->
789 </div><!-- #available-widgets -->
790 </div><!-- #widgets-left -->
795 * Calls admin_print_footer_scripts and admin_print_scripts hooks to
796 * allow custom scripts from plugins.
801 public function print_footer_scripts() {
802 /** This action is documented in wp-admin/admin-footer.php */
803 do_action( 'admin_print_footer_scripts-widgets.php' );
805 /** This action is documented in wp-admin/admin-footer.php */
806 do_action( 'admin_print_footer_scripts' );
808 /** This action is documented in wp-admin/admin-footer.php */
809 do_action( 'admin_footer-widgets.php' );
813 * Retrieves common arguments to supply when constructing a Customizer setting.
818 * @param string $id Widget setting ID.
819 * @param array $overrides Array of setting overrides.
820 * @return array Possibly modified setting arguments.
822 public function get_setting_args( $id, $overrides = array() ) {
825 'capability' => 'edit_theme_options',
826 'default' => array(),
829 if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
830 $args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
831 $args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
832 $args['transport'] = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
833 } elseif ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
834 $args['sanitize_callback'] = array( $this, 'sanitize_widget_instance' );
835 $args['sanitize_js_callback'] = array( $this, 'sanitize_widget_js_instance' );
836 $args['transport'] = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
839 $args = array_merge( $args, $overrides );
842 * Filters the common arguments supplied when constructing a Customizer setting.
846 * @see WP_Customize_Setting
848 * @param array $args Array of Customizer setting arguments.
849 * @param string $id Widget setting ID.
851 return apply_filters( 'widget_customizer_setting_args', $args, $id );
855 * Ensures sidebar widget arrays only ever contain widget IDS.
857 * Used as the 'sanitize_callback' for each $sidebars_widgets setting.
862 * @param array $widget_ids Array of widget IDs.
863 * @return array Array of sanitized widget IDs.
865 public function sanitize_sidebar_widgets( $widget_ids ) {
866 $widget_ids = array_map( 'strval', (array) $widget_ids );
867 $sanitized_widget_ids = array();
868 foreach ( $widget_ids as $widget_id ) {
869 $sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
871 return $sanitized_widget_ids;
875 * Builds up an index of all available widgets for use in Backbone models.
880 * @global array $wp_registered_widgets
881 * @global array $wp_registered_widget_controls
882 * @staticvar array $available_widgets
884 * @see wp_list_widgets()
886 * @return array List of available widgets.
888 public function get_available_widgets() {
889 static $available_widgets = array();
890 if ( ! empty( $available_widgets ) ) {
891 return $available_widgets;
894 global $wp_registered_widgets, $wp_registered_widget_controls;
895 require_once ABSPATH . '/wp-admin/includes/widgets.php'; // for next_widget_id_number()
897 $sort = $wp_registered_widgets;
898 usort( $sort, array( $this, '_sort_name_callback' ) );
901 foreach ( $sort as $widget ) {
902 if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget
906 $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
907 $done[] = $widget['callback'];
909 if ( ! isset( $widget['params'][0] ) ) {
910 $widget['params'][0] = array();
913 $available_widget = $widget;
914 unset( $available_widget['callback'] ); // not serializable to JSON
917 'widget_id' => $widget['id'],
918 'widget_name' => $widget['name'],
919 '_display' => 'template',
922 $is_disabled = false;
923 $is_multi_widget = ( isset( $wp_registered_widget_controls[$widget['id']]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
924 if ( $is_multi_widget ) {
925 $id_base = $wp_registered_widget_controls[$widget['id']]['id_base'];
926 $args['_temp_id'] = "$id_base-__i__";
927 $args['_multi_num'] = next_widget_id_number( $id_base );
928 $args['_add'] = 'multi';
930 $args['_add'] = 'single';
932 if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
935 $id_base = $widget['id'];
938 $list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar( array( 0 => $args, 1 => $widget['params'][0] ) );
939 $control_tpl = $this->get_widget_control( $list_widget_controls_args );
941 // The properties here are mapped to the Backbone Widget model.
942 $available_widget = array_merge( $available_widget, array(
943 'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
944 'is_multi' => $is_multi_widget,
945 'control_tpl' => $control_tpl,
946 'multi_number' => ( $args['_add'] === 'multi' ) ? $args['_multi_num'] : false,
947 'is_disabled' => $is_disabled,
948 'id_base' => $id_base,
949 'transport' => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
950 'width' => $wp_registered_widget_controls[$widget['id']]['width'],
951 'height' => $wp_registered_widget_controls[$widget['id']]['height'],
952 'is_wide' => $this->is_wide_widget( $widget['id'] ),
955 $available_widgets[] = $available_widget;
958 return $available_widgets;
962 * Naturally orders available widgets by name.
967 * @param array $widget_a The first widget to compare.
968 * @param array $widget_b The second widget to compare.
969 * @return int Reorder position for the current widget comparison.
971 protected function _sort_name_callback( $widget_a, $widget_b ) {
972 return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
976 * Retrieves the widget control markup.
981 * @param array $args Widget control arguments.
982 * @return string Widget control form HTML markup.
984 public function get_widget_control( $args ) {
985 $args[0]['before_form'] = '<div class="form">';
986 $args[0]['after_form'] = '</div><!-- .form -->';
987 $args[0]['before_widget_content'] = '<div class="widget-content">';
988 $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
990 call_user_func_array( 'wp_widget_control', $args );
991 $control_tpl = ob_get_clean();
996 * Retrieves the widget control markup parts.
1001 * @param array $args Widget control arguments.
1003 * @type string $control Markup for widget control wrapping form.
1004 * @type string $content The contents of the widget form itself.
1007 public function get_widget_control_parts( $args ) {
1008 $args[0]['before_widget_content'] = '<div class="widget-content">';
1009 $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
1010 $control_markup = $this->get_widget_control( $args );
1012 $content_start_pos = strpos( $control_markup, $args[0]['before_widget_content'] );
1013 $content_end_pos = strrpos( $control_markup, $args[0]['after_widget_content'] );
1015 $control = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
1016 $control .= substr( $control_markup, $content_end_pos );
1017 $content = trim( substr(
1019 $content_start_pos + strlen( $args[0]['before_widget_content'] ),
1020 $content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
1023 return compact( 'control', 'content' );
1027 * Adds hooks for the Customizer preview.
1032 public function customize_preview_init() {
1033 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
1034 add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
1035 add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
1039 * Refreshes the nonce for widget updates.
1044 * @param array $nonces Array of nonces.
1045 * @return array $nonces Array of nonces.
1047 public function refresh_nonces( $nonces ) {
1048 $nonces['update-widget'] = wp_create_nonce( 'update-widget' );
1053 * When previewing, ensures the proper previewing widgets are used.
1055 * Because wp_get_sidebars_widgets() gets called early at {@see 'init' } (via
1056 * wp_convert_widget_settings()) and can set global variable `$_wp_sidebars_widgets`
1057 * to the value of `get_option( 'sidebars_widgets' )` before the Customizer preview
1058 * filter is added, it has to be reset after the filter has been added.
1063 * @param array $sidebars_widgets List of widgets for the current sidebar.
1066 public function preview_sidebars_widgets( $sidebars_widgets ) {
1067 $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1069 unset( $sidebars_widgets['array_version'] );
1070 return $sidebars_widgets;
1074 * Enqueues scripts for the Customizer preview.
1079 public function customize_preview_enqueue() {
1080 wp_enqueue_script( 'customize-preview-widgets' );
1081 wp_enqueue_style( 'customize-preview' );
1085 * Inserts default style for highlighted widget at early point so theme
1086 * stylesheet can override.
1091 public function print_preview_css() {
1094 .widget-customizer-highlighted-widget {
1096 -webkit-box-shadow: 0 0 2px rgba(30,140,190,0.8);
1097 box-shadow: 0 0 2px rgba(30,140,190,0.8);
1106 * Communicates the sidebars that appeared on the page at the very end of the page,
1107 * and at the very end of the wp_footer,
1112 * @global array $wp_registered_sidebars
1113 * @global array $wp_registered_widgets
1115 public function export_preview_data() {
1116 global $wp_registered_sidebars, $wp_registered_widgets;
1118 // Prepare Customizer settings to pass to JavaScript.
1120 'renderedSidebars' => array_fill_keys( array_unique( $this->rendered_sidebars ), true ),
1121 'renderedWidgets' => array_fill_keys( array_keys( $this->rendered_widgets ), true ),
1122 'registeredSidebars' => array_values( $wp_registered_sidebars ),
1123 'registeredWidgets' => $wp_registered_widgets,
1125 'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
1127 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
1129 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
1130 unset( $registered_widget['callback'] ); // may not be JSON-serializeable
1134 <script type="text/javascript">
1135 var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
1141 * Tracks the widgets that were rendered.
1146 * @param array $widget Rendered widget to tally.
1148 public function tally_rendered_widgets( $widget ) {
1149 $this->rendered_widgets[ $widget['id'] ] = true;
1153 * Determine if a widget is rendered on the page.
1158 * @param string $widget_id Widget ID to check.
1159 * @return bool Whether the widget is rendered.
1161 public function is_widget_rendered( $widget_id ) {
1162 return in_array( $widget_id, $this->rendered_widgets );
1166 * Determines if a sidebar is rendered on the page.
1171 * @param string $sidebar_id Sidebar ID to check.
1172 * @return bool Whether the sidebar is rendered.
1174 public function is_sidebar_rendered( $sidebar_id ) {
1175 return in_array( $sidebar_id, $this->rendered_sidebars );
1179 * Tallies the sidebars rendered via is_active_sidebar().
1181 * Keep track of the times that is_active_sidebar() is called in the template,
1182 * and assume that this means that the sidebar would be rendered on the template
1183 * if there were widgets populating it.
1188 * @param bool $is_active Whether the sidebar is active.
1189 * @param string $sidebar_id Sidebar ID.
1190 * @return bool Whether the sidebar is active.
1192 public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
1193 if ( is_registered_sidebar( $sidebar_id ) ) {
1194 $this->rendered_sidebars[] = $sidebar_id;
1197 * We may need to force this to true, and also force-true the value
1198 * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
1199 * is an area to drop widgets into, if the sidebar is empty.
1205 * Tallies the sidebars rendered via dynamic_sidebar().
1207 * Keep track of the times that dynamic_sidebar() is called in the template,
1208 * and assume this means the sidebar would be rendered on the template if
1209 * there were widgets populating it.
1214 * @param bool $has_widgets Whether the current sidebar has widgets.
1215 * @param string $sidebar_id Sidebar ID.
1216 * @return bool Whether the current sidebar has widgets.
1218 public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
1219 if ( is_registered_sidebar( $sidebar_id ) ) {
1220 $this->rendered_sidebars[] = $sidebar_id;
1224 * We may need to force this to true, and also force-true the value
1225 * for 'is_active_sidebar' if we want to ensure there is an area to
1226 * drop widgets into, if the sidebar is empty.
1228 return $has_widgets;
1232 * Retrieves MAC for a serialized widget instance string.
1234 * Allows values posted back from JS to be rejected if any tampering of the
1235 * data has occurred.
1240 * @param string $serialized_instance Widget instance.
1241 * @return string MAC for serialized widget instance.
1243 protected function get_instance_hash_key( $serialized_instance ) {
1244 return wp_hash( $serialized_instance );
1248 * Sanitizes a widget instance.
1250 * Unserialize the JS-instance for storing in the options. It's important that this filter
1251 * only get applied to an instance *once*.
1256 * @param array $value Widget instance to sanitize.
1257 * @return array|void Sanitized widget instance.
1259 public function sanitize_widget_instance( $value ) {
1260 if ( $value === array() ) {
1264 if ( empty( $value['is_widget_customizer_js_value'] )
1265 || empty( $value['instance_hash_key'] )
1266 || empty( $value['encoded_serialized_instance'] ) )
1271 $decoded = base64_decode( $value['encoded_serialized_instance'], true );
1272 if ( false === $decoded ) {
1276 if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
1280 $instance = unserialize( $decoded );
1281 if ( false === $instance ) {
1289 * Converts a widget instance into JSON-representable format.
1294 * @param array $value Widget instance to convert to JSON.
1295 * @return array JSON-converted widget instance.
1297 public function sanitize_widget_js_instance( $value ) {
1298 if ( empty( $value['is_widget_customizer_js_value'] ) ) {
1299 $serialized = serialize( $value );
1302 'encoded_serialized_instance' => base64_encode( $serialized ),
1303 'title' => empty( $value['title'] ) ? '' : $value['title'],
1304 'is_widget_customizer_js_value' => true,
1305 'instance_hash_key' => $this->get_instance_hash_key( $serialized ),
1312 * Strips out widget IDs for widgets which are no longer registered.
1314 * One example where this might happen is when a plugin orphans a widget
1315 * in a sidebar upon deactivation.
1320 * @global array $wp_registered_widgets
1322 * @param array $widget_ids List of widget IDs.
1323 * @return array Parsed list of widget IDs.
1325 public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
1326 global $wp_registered_widgets;
1327 $widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
1332 * Finds and invokes the widget update and control callbacks.
1334 * Requires that `$_POST` be populated with the instance data.
1339 * @global array $wp_registered_widget_updates
1340 * @global array $wp_registered_widget_controls
1342 * @param string $widget_id Widget ID.
1343 * @return WP_Error|array Array containing the updated widget information.
1344 * A WP_Error object, otherwise.
1346 public function call_widget_update( $widget_id ) {
1347 global $wp_registered_widget_updates, $wp_registered_widget_controls;
1349 $setting_id = $this->get_setting_id( $widget_id );
1352 * Make sure that other setting changes have previewed since this widget
1353 * may depend on them (e.g. Menus being present for Custom Menu widget).
1355 if ( ! did_action( 'customize_preview_init' ) ) {
1356 foreach ( $this->manager->settings() as $setting ) {
1357 if ( $setting->id !== $setting_id ) {
1358 $setting->preview();
1363 $this->start_capturing_option_updates();
1364 $parsed_id = $this->parse_widget_id( $widget_id );
1365 $option_name = 'widget_' . $parsed_id['id_base'];
1368 * If a previously-sanitized instance is provided, populate the input vars
1369 * with its values so that the widget update callback will read this instance
1371 $added_input_vars = array();
1372 if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
1373 $sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
1374 if ( false === $sanitized_widget_setting ) {
1375 $this->stop_capturing_option_updates();
1376 return new WP_Error( 'widget_setting_malformed' );
1379 $instance = $this->sanitize_widget_instance( $sanitized_widget_setting );
1380 if ( is_null( $instance ) ) {
1381 $this->stop_capturing_option_updates();
1382 return new WP_Error( 'widget_setting_unsanitized' );
1385 if ( ! is_null( $parsed_id['number'] ) ) {
1387 $value[$parsed_id['number']] = $instance;
1388 $key = 'widget-' . $parsed_id['id_base'];
1389 $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1390 $added_input_vars[] = $key;
1392 foreach ( $instance as $key => $value ) {
1393 $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1394 $added_input_vars[] = $key;
1399 // Invoke the widget update callback.
1400 foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
1401 if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
1403 call_user_func_array( $control['callback'], $control['params'] );
1409 // Clean up any input vars that were manually added
1410 foreach ( $added_input_vars as $key ) {
1411 unset( $_POST[ $key ] );
1412 unset( $_REQUEST[ $key ] );
1415 // Make sure the expected option was updated.
1416 if ( 0 !== $this->count_captured_options() ) {
1417 if ( $this->count_captured_options() > 1 ) {
1418 $this->stop_capturing_option_updates();
1419 return new WP_Error( 'widget_setting_too_many_options' );
1422 $updated_option_name = key( $this->get_captured_options() );
1423 if ( $updated_option_name !== $option_name ) {
1424 $this->stop_capturing_option_updates();
1425 return new WP_Error( 'widget_setting_unexpected_option' );
1429 // Obtain the widget instance.
1430 $option = $this->get_captured_option( $option_name );
1431 if ( null !== $parsed_id['number'] ) {
1432 $instance = $option[ $parsed_id['number'] ];
1434 $instance = $option;
1438 * Override the incoming $_POST['customized'] for a newly-created widget's
1439 * setting with the new $instance so that the preview filter currently
1440 * in place from WP_Customize_Setting::preview() will use this value
1441 * instead of the default widget instance value (an empty array).
1443 $this->manager->set_post_value( $setting_id, $this->sanitize_widget_js_instance( $instance ) );
1445 // Obtain the widget control with the updated instance in place.
1447 $form = $wp_registered_widget_controls[ $widget_id ];
1449 call_user_func_array( $form['callback'], $form['params'] );
1451 $form = ob_get_clean();
1453 $this->stop_capturing_option_updates();
1455 return compact( 'instance', 'form' );
1459 * Updates widget settings asynchronously.
1461 * Allows the Customizer to update a widget using its form, but return the new
1462 * instance info via Ajax instead of saving it to the options table.
1464 * Most code here copied from wp_ajax_save_widget().
1469 * @see wp_ajax_save_widget()
1471 public function wp_ajax_update_widget() {
1473 if ( ! is_user_logged_in() ) {
1477 check_ajax_referer( 'update-widget', 'nonce' );
1479 if ( ! current_user_can( 'edit_theme_options' ) ) {
1483 if ( empty( $_POST['widget-id'] ) ) {
1484 wp_send_json_error( 'missing_widget-id' );
1487 /** This action is documented in wp-admin/includes/ajax-actions.php */
1488 do_action( 'load-widgets.php' );
1490 /** This action is documented in wp-admin/includes/ajax-actions.php */
1491 do_action( 'widgets.php' );
1493 /** This action is documented in wp-admin/widgets.php */
1494 do_action( 'sidebar_admin_setup' );
1496 $widget_id = $this->get_post_value( 'widget-id' );
1497 $parsed_id = $this->parse_widget_id( $widget_id );
1498 $id_base = $parsed_id['id_base'];
1500 $is_updating_widget_template = (
1501 isset( $_POST[ 'widget-' . $id_base ] )
1503 is_array( $_POST[ 'widget-' . $id_base ] )
1505 preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
1507 if ( $is_updating_widget_template ) {
1508 wp_send_json_error( 'template_widget_not_updatable' );
1511 $updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
1512 if ( is_wp_error( $updated_widget ) ) {
1513 wp_send_json_error( $updated_widget->get_error_code() );
1516 $form = $updated_widget['form'];
1517 $instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );
1519 wp_send_json_success( compact( 'form', 'instance' ) );
1523 * Selective Refresh Methods
1527 * Filters arguments for dynamic widget partials.
1532 * @param array|false $partial_args Partial arguments.
1533 * @param string $partial_id Partial ID.
1534 * @return array (Maybe) modified partial arguments.
1536 public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1537 if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
1538 return $partial_args;
1541 if ( preg_match( '/^widget\[(?P<widget_id>.+)\]$/', $partial_id, $matches ) ) {
1542 if ( false === $partial_args ) {
1543 $partial_args = array();
1545 $partial_args = array_merge(
1549 'render_callback' => array( $this, 'render_widget_partial' ),
1550 'container_inclusive' => true,
1551 'settings' => array( $this->get_setting_id( $matches['widget_id'] ) ),
1552 'capability' => 'edit_theme_options',
1557 return $partial_args;
1561 * Adds hooks for selective refresh.
1566 public function selective_refresh_init() {
1567 if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
1570 add_filter( 'dynamic_sidebar_params', array( $this, 'filter_dynamic_sidebar_params' ) );
1571 add_filter( 'wp_kses_allowed_html', array( $this, 'filter_wp_kses_allowed_data_attributes' ) );
1572 add_action( 'dynamic_sidebar_before', array( $this, 'start_dynamic_sidebar' ) );
1573 add_action( 'dynamic_sidebar_after', array( $this, 'end_dynamic_sidebar' ) );
1577 * Inject selective refresh data attributes into widget container elements.
1579 * @param array $params {
1580 * Dynamic sidebar params.
1582 * @type array $args Sidebar args.
1583 * @type array $widget_args Widget args.
1585 * @see WP_Customize_Nav_Menus_Partial_Refresh::filter_wp_nav_menu_args()
1587 * @return array Params.
1589 public function filter_dynamic_sidebar_params( $params ) {
1590 $sidebar_args = array_merge(
1592 'before_widget' => '',
1593 'after_widget' => '',
1598 // Skip widgets not in a registered sidebar or ones which lack a proper wrapper element to attach the data-* attributes to.
1601 isset( $sidebar_args['id'] )
1603 is_registered_sidebar( $sidebar_args['id'] )
1605 ( isset( $this->current_dynamic_sidebar_id_stack[0] ) && $this->current_dynamic_sidebar_id_stack[0] === $sidebar_args['id'] )
1607 preg_match( '#^<(?P<tag_name>\w+)#', $sidebar_args['before_widget'], $matches )
1609 if ( ! $is_valid ) {
1612 $this->before_widget_tags_seen[ $matches['tag_name'] ] = true;
1615 'sidebar_id' => $sidebar_args['id'],
1617 if ( isset( $this->context_sidebar_instance_number ) ) {
1618 $context['sidebar_instance_number'] = $this->context_sidebar_instance_number;
1619 } else if ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
1620 $context['sidebar_instance_number'] = $this->sidebar_instance_count[ $sidebar_args['id'] ];
1623 $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
1624 $attributes .= ' data-customize-partial-type="widget"';
1625 $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
1626 $attributes .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
1627 $sidebar_args['before_widget'] = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $sidebar_args['before_widget'] );
1629 $params[0] = $sidebar_args;
1634 * List of the tag names seen for before_widget strings.
1636 * This is used in the {@see 'filter_wp_kses_allowed_html'} filter to ensure that the
1637 * data-* attributes can be whitelisted.
1643 protected $before_widget_tags_seen = array();
1646 * Ensures the HTML data-* attributes for selective refresh are allowed by kses.
1648 * This is needed in case the `$before_widget` is run through wp_kses() when printed.
1653 * @param array $allowed_html Allowed HTML.
1654 * @return array (Maybe) modified allowed HTML.
1656 public function filter_wp_kses_allowed_data_attributes( $allowed_html ) {
1657 foreach ( array_keys( $this->before_widget_tags_seen ) as $tag_name ) {
1658 if ( ! isset( $allowed_html[ $tag_name ] ) ) {
1659 $allowed_html[ $tag_name ] = array();
1661 $allowed_html[ $tag_name ] = array_merge(
1662 $allowed_html[ $tag_name ],
1663 array_fill_keys( array(
1664 'data-customize-partial-id',
1665 'data-customize-partial-type',
1666 'data-customize-partial-placement-context',
1667 'data-customize-partial-widget-id',
1668 'data-customize-partial-options',
1672 return $allowed_html;
1676 * Keep track of the number of times that dynamic_sidebar() was called for a given sidebar index.
1678 * This helps facilitate the uncommon scenario where a single sidebar is rendered multiple times on a template.
1684 protected $sidebar_instance_count = array();
1687 * The current request's sidebar_instance_number context.
1693 protected $context_sidebar_instance_number;
1696 * Current sidebar ID being rendered.
1702 protected $current_dynamic_sidebar_id_stack = array();
1705 * Begins keeping track of the current sidebar being rendered.
1707 * Insert marker before widgets are rendered in a dynamic sidebar.
1712 * @param int|string $index Index, name, or ID of the dynamic sidebar.
1714 public function start_dynamic_sidebar( $index ) {
1715 array_unshift( $this->current_dynamic_sidebar_id_stack, $index );
1716 if ( ! isset( $this->sidebar_instance_count[ $index ] ) ) {
1717 $this->sidebar_instance_count[ $index ] = 0;
1719 $this->sidebar_instance_count[ $index ] += 1;
1720 if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
1721 printf( "\n<!--dynamic_sidebar_before:%s:%d-->\n", esc_html( $index ), intval( $this->sidebar_instance_count[ $index ] ) );
1726 * Finishes keeping track of the current sidebar being rendered.
1728 * Inserts a marker after widgets are rendered in a dynamic sidebar.
1733 * @param int|string $index Index, name, or ID of the dynamic sidebar.
1735 public function end_dynamic_sidebar( $index ) {
1736 array_shift( $this->current_dynamic_sidebar_id_stack );
1737 if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
1738 printf( "\n<!--dynamic_sidebar_after:%s:%d-->\n", esc_html( $index ), intval( $this->sidebar_instance_count[ $index ] ) );
1743 * Current sidebar being rendered.
1749 protected $rendering_widget_id;
1752 * Current widget being rendered.
1758 protected $rendering_sidebar_id;
1761 * Filters sidebars_widgets to ensure the currently-rendered widget is the only widget in the current sidebar.
1766 * @param array $sidebars_widgets Sidebars widgets.
1767 * @return array Filtered sidebars widgets.
1769 public function filter_sidebars_widgets_for_rendering_widget( $sidebars_widgets ) {
1770 $sidebars_widgets[ $this->rendering_sidebar_id ] = array( $this->rendering_widget_id );
1771 return $sidebars_widgets;
1775 * Renders a specific widget using the supplied sidebar arguments.
1780 * @see dynamic_sidebar()
1782 * @param WP_Customize_Partial $partial Partial.
1783 * @param array $context {
1784 * Sidebar args supplied as container context.
1786 * @type string $sidebar_id ID for sidebar for widget to render into.
1787 * @type int $sidebar_instance_number Disambiguating instance number.
1789 * @return string|false
1791 public function render_widget_partial( $partial, $context ) {
1792 $id_data = $partial->id_data();
1793 $widget_id = array_shift( $id_data['keys'] );
1795 if ( ! is_array( $context )
1796 || empty( $context['sidebar_id'] )
1797 || ! is_registered_sidebar( $context['sidebar_id'] )
1802 $this->rendering_sidebar_id = $context['sidebar_id'];
1804 if ( isset( $context['sidebar_instance_number'] ) ) {
1805 $this->context_sidebar_instance_number = intval( $context['sidebar_instance_number'] );
1808 // Filter sidebars_widgets so that only the queried widget is in the sidebar.
1809 $this->rendering_widget_id = $widget_id;
1811 $filter_callback = array( $this, 'filter_sidebars_widgets_for_rendering_widget' );
1812 add_filter( 'sidebars_widgets', $filter_callback, 1000 );
1814 // Render the widget.
1816 dynamic_sidebar( $this->rendering_sidebar_id = $context['sidebar_id'] );
1817 $container = ob_get_clean();
1819 // Reset variables for next partial render.
1820 remove_filter( 'sidebars_widgets', $filter_callback, 1000 );
1822 $this->context_sidebar_instance_number = null;
1823 $this->rendering_sidebar_id = null;
1824 $this->rendering_widget_id = null;
1830 // Option Update Capturing
1834 * List of captured widget option updates.
1838 * @var array $_captured_options Values updated while option capture is happening.
1840 protected $_captured_options = array();
1843 * Whether option capture is currently happening.
1847 * @var bool $_is_current Whether option capture is currently happening or not.
1849 protected $_is_capturing_option_updates = false;
1852 * Determines whether the captured option update should be ignored.
1857 * @param string $option_name Option name.
1858 * @return bool Whether the option capture is ignored.
1860 protected function is_option_capture_ignored( $option_name ) {
1861 return ( 0 === strpos( $option_name, '_transient_' ) );
1865 * Retrieves captured widget option updates.
1870 * @return array Array of captured options.
1872 protected function get_captured_options() {
1873 return $this->_captured_options;
1877 * Retrieves the option that was captured from being saved.
1882 * @param string $option_name Option name.
1883 * @param mixed $default Optional. Default value to return if the option does not exist. Default false.
1884 * @return mixed Value set for the option.
1886 protected function get_captured_option( $option_name, $default = false ) {
1887 if ( array_key_exists( $option_name, $this->_captured_options ) ) {
1888 $value = $this->_captured_options[ $option_name ];
1896 * Retrieves the number of captured widget option updates.
1901 * @return int Number of updated options.
1903 protected function count_captured_options() {
1904 return count( $this->_captured_options );
1908 * Begins keeping track of changes to widget options, caching new values.
1913 protected function start_capturing_option_updates() {
1914 if ( $this->_is_capturing_option_updates ) {
1918 $this->_is_capturing_option_updates = true;
1920 add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
1924 * Pre-filters captured option values before updating.
1929 * @param mixed $new_value The new option value.
1930 * @param string $option_name Name of the option.
1931 * @param mixed $old_value The old option value.
1932 * @return mixed Filtered option value.
1934 public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
1935 if ( $this->is_option_capture_ignored( $option_name ) ) {
1939 if ( ! isset( $this->_captured_options[ $option_name ] ) ) {
1940 add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1943 $this->_captured_options[ $option_name ] = $new_value;
1949 * Pre-filters captured option values before retrieving.
1954 * @param mixed $value Value to return instead of the option value.
1955 * @return mixed Filtered option value.
1957 public function capture_filter_pre_get_option( $value ) {
1958 $option_name = preg_replace( '/^pre_option_/', '', current_filter() );
1960 if ( isset( $this->_captured_options[ $option_name ] ) ) {
1961 $value = $this->_captured_options[ $option_name ];
1963 /** This filter is documented in wp-includes/option.php */
1964 $value = apply_filters( 'option_' . $option_name, $value );
1971 * Undoes any changes to the options since options capture began.
1976 protected function stop_capturing_option_updates() {
1977 if ( ! $this->_is_capturing_option_updates ) {
1981 remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10 );
1983 foreach ( array_keys( $this->_captured_options ) as $option_name ) {
1984 remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1987 $this->_captured_options = array();
1988 $this->_is_capturing_option_updates = false;
1992 * {@internal Missing Summary}
1994 * See the {@see 'customize_dynamic_setting_args'} filter.
1997 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
1999 public function setup_widget_addition_previews() {
2000 _deprecated_function( __METHOD__, '4.2.0' );
2004 * {@internal Missing Summary}
2006 * See the {@see 'customize_dynamic_setting_args'} filter.
2009 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2011 public function prepreview_added_sidebars_widgets() {
2012 _deprecated_function( __METHOD__, '4.2.0' );
2016 * {@internal Missing Summary}
2018 * See the {@see 'customize_dynamic_setting_args'} filter.
2021 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2023 public function prepreview_added_widget_instance() {
2024 _deprecated_function( __METHOD__, '4.2.0' );
2028 * {@internal Missing Summary}
2030 * See the {@see 'customize_dynamic_setting_args'} filter.
2033 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2035 public function remove_prepreview_filters() {
2036 _deprecated_function( __METHOD__, '4.2.0' );