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 // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
97 add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
98 add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
99 add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
101 // Skip remaining hooks when the user can't manage widgets anyway.
102 if ( ! current_user_can( 'edit_theme_options' ) ) {
106 add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
107 add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
108 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
109 add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
110 add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
111 add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
112 add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
113 add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
114 add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
116 add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
117 add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
118 add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
120 // Selective Refresh.
121 add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
122 add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
126 * List whether each registered widget can be use selective refresh.
128 * If the theme does not support the customize-selective-refresh-widgets feature,
129 * then this will always return an empty array.
134 * @return array Mapping of id_base to support. If theme doesn't support
135 * selective refresh, an empty array is returned.
137 public function get_selective_refreshable_widgets() {
138 global $wp_widget_factory;
139 if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
142 if ( ! isset( $this->selective_refreshable_widgets ) ) {
143 $this->selective_refreshable_widgets = array();
144 foreach ( $wp_widget_factory->widgets as $wp_widget ) {
145 $this->selective_refreshable_widgets[ $wp_widget->id_base ] = ! empty( $wp_widget->widget_options['customize_selective_refresh'] );
148 return $this->selective_refreshable_widgets;
152 * Determines if a widget supports selective refresh.
157 * @param string $id_base Widget ID Base.
158 * @return bool Whether the widget can be selective refreshed.
160 public function is_widget_selective_refreshable( $id_base ) {
161 $selective_refreshable_widgets = $this->get_selective_refreshable_widgets();
162 return ! empty( $selective_refreshable_widgets[ $id_base ] );
166 * Retrieves the widget setting type given a setting ID.
171 * @staticvar array $cache
173 * @param string $setting_id Setting ID.
174 * @return string|void Setting type.
176 protected function get_setting_type( $setting_id ) {
177 static $cache = array();
178 if ( isset( $cache[ $setting_id ] ) ) {
179 return $cache[ $setting_id ];
181 foreach ( $this->setting_id_patterns as $type => $pattern ) {
182 if ( preg_match( $pattern, $setting_id ) ) {
183 $cache[ $setting_id ] = $type;
190 * Inspects the incoming customized data for any widget settings, and dynamically adds
191 * them up-front so widgets will be initialized properly.
196 public function register_settings() {
197 $widget_setting_ids = array();
198 $incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
199 foreach ( $incoming_setting_ids as $setting_id ) {
200 if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
201 $widget_setting_ids[] = $setting_id;
204 if ( $this->manager->doing_ajax( 'update-widget' ) && isset( $_REQUEST['widget-id'] ) ) {
205 $widget_setting_ids[] = $this->get_setting_id( wp_unslash( $_REQUEST['widget-id'] ) );
208 $settings = $this->manager->add_dynamic_settings( array_unique( $widget_setting_ids ) );
211 * Preview settings right away so that widgets and sidebars will get registered properly.
212 * But don't do this if a customize_save because this will cause WP to think there is nothing
213 * changed that needs to be saved.
215 if ( ! $this->manager->doing_ajax( 'customize_save' ) ) {
216 foreach ( $settings as $setting ) {
223 * Determines the arguments for a dynamically-created setting.
228 * @param false|array $args The arguments to the WP_Customize_Setting constructor.
229 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
230 * @return false|array Setting arguments, false otherwise.
232 public function filter_customize_dynamic_setting_args( $args, $setting_id ) {
233 if ( $this->get_setting_type( $setting_id ) ) {
234 $args = $this->get_setting_args( $setting_id );
240 * Retrieves an unslashed post value or return a default.
245 * @param string $name Post value.
246 * @param mixed $default Default post value.
247 * @return mixed Unslashed post value or default value.
249 protected function get_post_value( $name, $default = null ) {
250 if ( ! isset( $_POST[ $name ] ) ) {
254 return wp_unslash( $_POST[ $name ] );
258 * Override sidebars_widgets for theme switch.
260 * When switching a theme via the Customizer, supply any previously-configured
261 * sidebars_widgets from the target theme as the initial sidebars_widgets
262 * setting. Also store the old theme's existing settings so that they can
263 * be passed along for storing in the sidebars_widgets theme_mod when the
264 * theme gets switched.
269 * @global array $sidebars_widgets
270 * @global array $_wp_sidebars_widgets
272 public function override_sidebars_widgets_for_theme_switch() {
273 global $sidebars_widgets;
275 if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
279 $this->old_sidebars_widgets = wp_get_sidebars_widgets();
280 add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
281 $this->manager->set_post_value( 'old_sidebars_widgets_data', $this->old_sidebars_widgets ); // Override any value cached in changeset.
283 // retrieve_widgets() looks at the global $sidebars_widgets
284 $sidebars_widgets = $this->old_sidebars_widgets;
285 $sidebars_widgets = retrieve_widgets( 'customize' );
286 add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
287 // reset global cache var used by wp_get_sidebars_widgets()
288 unset( $GLOBALS['_wp_sidebars_widgets'] );
292 * Filters old_sidebars_widgets_data Customizer setting.
294 * When switching themes, filter the Customizer setting old_sidebars_widgets_data
295 * to supply initial $sidebars_widgets before they were overridden by retrieve_widgets().
296 * The value for old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
302 * @see WP_Customize_Widgets::handle_theme_switch()
304 * @param array $old_sidebars_widgets
307 public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
308 return $this->old_sidebars_widgets;
312 * Filters sidebars_widgets option for theme switch.
314 * When switching themes, the retrieve_widgets() function is run when the Customizer initializes,
315 * and then the new sidebars_widgets here get supplied as the default value for the sidebars_widgets
321 * @see WP_Customize_Widgets::handle_theme_switch()
322 * @global array $sidebars_widgets
324 * @param array $sidebars_widgets
327 public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
328 $sidebars_widgets = $GLOBALS['sidebars_widgets'];
329 $sidebars_widgets['array_version'] = 3;
330 return $sidebars_widgets;
334 * Ensures all widgets get loaded into the Customizer.
336 * Note: these actions are also fired in wp_ajax_update_widget().
341 public function customize_controls_init() {
342 /** This action is documented in wp-admin/includes/ajax-actions.php */
343 do_action( 'load-widgets.php' );
345 /** This action is documented in wp-admin/includes/ajax-actions.php */
346 do_action( 'widgets.php' );
348 /** This action is documented in wp-admin/widgets.php */
349 do_action( 'sidebar_admin_setup' );
353 * Ensures widgets are available for all types of previews.
355 * When in preview, hook to {@see 'customize_register'} for settings after WordPress is loaded
356 * so that all filters have been initialized (e.g. Widget Visibility).
361 public function schedule_customize_register() {
363 $this->customize_register();
365 add_action( 'wp', array( $this, 'customize_register' ) );
370 * Registers Customizer settings and controls for all sidebars and widgets.
375 * @global array $wp_registered_widgets
376 * @global array $wp_registered_widget_controls
377 * @global array $wp_registered_sidebars
379 public function customize_register() {
380 global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
382 add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
384 $sidebars_widgets = array_merge(
385 array( 'wp_inactive_widgets' => array() ),
386 array_fill_keys( array_keys( $wp_registered_sidebars ), array() ),
387 wp_get_sidebars_widgets()
390 $new_setting_ids = array();
393 * Register a setting for all widgets, including those which are active,
394 * inactive, and orphaned since a widget may get suppressed from a sidebar
395 * via a plugin (like Widget Visibility).
397 foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
398 $setting_id = $this->get_setting_id( $widget_id );
399 $setting_args = $this->get_setting_args( $setting_id );
400 if ( ! $this->manager->get_setting( $setting_id ) ) {
401 $this->manager->add_setting( $setting_id, $setting_args );
403 $new_setting_ids[] = $setting_id;
407 * Add a setting which will be supplied for the theme's sidebars_widgets
408 * theme_mod when the theme is switched.
410 if ( ! $this->manager->is_theme_active() ) {
411 $setting_id = 'old_sidebars_widgets_data';
412 $setting_args = $this->get_setting_args( $setting_id, array(
413 'type' => 'global_variable',
416 $this->manager->add_setting( $setting_id, $setting_args );
419 $this->manager->add_panel( 'widgets', array(
421 'title' => __( 'Widgets' ),
422 'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
424 'active_callback' => array( $this, 'is_panel_active' ),
427 foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
428 if ( empty( $sidebar_widget_ids ) ) {
429 $sidebar_widget_ids = array();
432 $is_registered_sidebar = is_registered_sidebar( $sidebar_id );
433 $is_inactive_widgets = ( 'wp_inactive_widgets' === $sidebar_id );
434 $is_active_sidebar = ( $is_registered_sidebar && ! $is_inactive_widgets );
436 // Add setting for managing the sidebar's widgets.
437 if ( $is_registered_sidebar || $is_inactive_widgets ) {
438 $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
439 $setting_args = $this->get_setting_args( $setting_id );
440 if ( ! $this->manager->get_setting( $setting_id ) ) {
441 if ( ! $this->manager->is_theme_active() ) {
442 $setting_args['dirty'] = true;
444 $this->manager->add_setting( $setting_id, $setting_args );
446 $new_setting_ids[] = $setting_id;
448 // Add section to contain controls.
449 $section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
450 if ( $is_active_sidebar ) {
452 $section_args = array(
453 'title' => $wp_registered_sidebars[ $sidebar_id ]['name'],
454 'description' => $wp_registered_sidebars[ $sidebar_id ]['description'],
455 'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ) ),
456 'panel' => 'widgets',
457 'sidebar_id' => $sidebar_id,
461 * Filters Customizer widget section arguments for a given sidebar.
465 * @param array $section_args Array of Customizer widget section arguments.
466 * @param string $section_id Customizer section ID.
467 * @param int|string $sidebar_id Sidebar ID.
469 $section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
471 $section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
472 $this->manager->add_section( $section );
474 $control = new WP_Widget_Area_Customize_Control( $this->manager, $setting_id, array(
475 'section' => $section_id,
476 'sidebar_id' => $sidebar_id,
477 'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
479 $new_setting_ids[] = $setting_id;
481 $this->manager->add_control( $control );
485 // Add a control for each active widget (located in a sidebar).
486 foreach ( $sidebar_widget_ids as $i => $widget_id ) {
488 // Skip widgets that may have gone away due to a plugin being deactivated.
489 if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[$widget_id] ) ) {
493 $registered_widget = $wp_registered_widgets[$widget_id];
494 $setting_id = $this->get_setting_id( $widget_id );
495 $id_base = $wp_registered_widget_controls[$widget_id]['id_base'];
497 $control = new WP_Widget_Form_Customize_Control( $this->manager, $setting_id, array(
498 'label' => $registered_widget['name'],
499 'section' => $section_id,
500 'sidebar_id' => $sidebar_id,
501 'widget_id' => $widget_id,
502 'widget_id_base' => $id_base,
504 'width' => $wp_registered_widget_controls[$widget_id]['width'],
505 'height' => $wp_registered_widget_controls[$widget_id]['height'],
506 'is_wide' => $this->is_wide_widget( $widget_id ),
508 $this->manager->add_control( $control );
512 if ( ! $this->manager->doing_ajax( 'customize_save' ) ) {
513 foreach ( $new_setting_ids as $new_setting_id ) {
514 $this->manager->get_setting( $new_setting_id )->preview();
520 * Determines whether the widgets panel is active, based on whether there are sidebars registered.
525 * @see WP_Customize_Panel::$active_callback
527 * @global array $wp_registered_sidebars
528 * @return bool Active.
530 public function is_panel_active() {
531 global $wp_registered_sidebars;
532 return ! empty( $wp_registered_sidebars );
536 * Converts a widget_id into its corresponding Customizer setting ID (option name).
541 * @param string $widget_id Widget ID.
542 * @return string Maybe-parsed widget ID.
544 public function get_setting_id( $widget_id ) {
545 $parsed_widget_id = $this->parse_widget_id( $widget_id );
546 $setting_id = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
548 if ( ! is_null( $parsed_widget_id['number'] ) ) {
549 $setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
555 * Determines whether the widget is considered "wide".
557 * Core widgets which may have controls wider than 250, but can still be shown
558 * in the narrow Customizer panel. The RSS and Text widgets in Core, for example,
559 * have widths of 400 and yet they still render fine in the Customizer panel.
561 * This method will return all Core widgets as being not wide, but this can be
562 * overridden with the {@see 'is_wide_widget_in_customizer'} filter.
567 * @global $wp_registered_widget_controls
569 * @param string $widget_id Widget ID.
570 * @return bool Whether or not the widget is a "wide" widget.
572 public function is_wide_widget( $widget_id ) {
573 global $wp_registered_widget_controls;
575 $parsed_widget_id = $this->parse_widget_id( $widget_id );
576 $width = $wp_registered_widget_controls[$widget_id]['width'];
577 $is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases );
578 $is_wide = ( $width > 250 && ! $is_core );
581 * Filters whether the given widget is considered "wide".
585 * @param bool $is_wide Whether the widget is wide, Default false.
586 * @param string $widget_id Widget ID.
588 return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
592 * Converts a widget ID into its id_base and number components.
597 * @param string $widget_id Widget ID.
598 * @return array Array containing a widget's id_base and number components.
600 public function parse_widget_id( $widget_id ) {
606 if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
607 $parsed['id_base'] = $matches[1];
608 $parsed['number'] = intval( $matches[2] );
610 // likely an old single widget
611 $parsed['id_base'] = $widget_id;
617 * Converts a widget setting ID (option path) to its id_base and number components.
622 * @param string $setting_id Widget setting ID.
623 * @return WP_Error|array Array containing a widget's id_base and number components,
624 * or a WP_Error object.
626 public function parse_widget_setting_id( $setting_id ) {
627 if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
628 return new WP_Error( 'widget_setting_invalid_id' );
631 $id_base = $matches[2];
632 $number = isset( $matches[3] ) ? intval( $matches[3] ) : null;
634 return compact( 'id_base', 'number' );
638 * Calls admin_print_styles-widgets.php and admin_print_styles hooks to
639 * allow custom styles from plugins.
644 public function print_styles() {
645 /** This action is documented in wp-admin/admin-header.php */
646 do_action( 'admin_print_styles-widgets.php' );
648 /** This action is documented in wp-admin/admin-header.php */
649 do_action( 'admin_print_styles' );
653 * Calls admin_print_scripts-widgets.php and admin_print_scripts hooks to
654 * allow custom scripts from plugins.
659 public function print_scripts() {
660 /** This action is documented in wp-admin/admin-header.php */
661 do_action( 'admin_print_scripts-widgets.php' );
663 /** This action is documented in wp-admin/admin-header.php */
664 do_action( 'admin_print_scripts' );
668 * Enqueues scripts and styles for Customizer panel and export data to JavaScript.
673 * @global WP_Scripts $wp_scripts
674 * @global array $wp_registered_sidebars
675 * @global array $wp_registered_widgets
677 public function enqueue_scripts() {
678 global $wp_scripts, $wp_registered_sidebars, $wp_registered_widgets;
680 wp_enqueue_style( 'customize-widgets' );
681 wp_enqueue_script( 'customize-widgets' );
683 /** This action is documented in wp-admin/admin-header.php */
684 do_action( 'admin_enqueue_scripts', 'widgets.php' );
687 * Export available widgets with control_tpl removed from model
688 * since plugins need templates to be in the DOM.
690 $available_widgets = array();
692 foreach ( $this->get_available_widgets() as $available_widget ) {
693 unset( $available_widget['control_tpl'] );
694 $available_widgets[] = $available_widget;
697 $widget_reorder_nav_tpl = sprintf(
698 '<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>',
699 __( 'Move to another area…' ),
704 $move_widget_area_tpl = str_replace(
705 array( '{description}', '{btn}' ),
707 __( 'Select an area to move this widget into:' ),
708 _x( 'Move', 'Move widget' ),
710 '<div class="move-widget-area">
711 <p class="description">{description}</p>
712 <ul class="widget-area-select">
713 <% _.each( sidebars, function ( sidebar ){ %>
714 <li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
717 <div class="move-widget-actions">
718 <button class="move-widget-btn button" type="button">{btn}</button>
724 'registeredSidebars' => array_values( $wp_registered_sidebars ),
725 'registeredWidgets' => $wp_registered_widgets,
726 'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets
728 'saveBtnLabel' => __( 'Apply' ),
729 'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
730 'removeBtnLabel' => __( 'Remove' ),
731 'removeBtnTooltip' => __( 'Trash widget by moving it to the inactive widgets sidebar.' ),
732 'error' => __( 'An error has occurred. Please reload the page and try again.' ),
733 'widgetMovedUp' => __( 'Widget moved up' ),
734 'widgetMovedDown' => __( 'Widget moved down' ),
735 'noAreasRendered' => __( 'There are no widget areas on the page shown, however other pages in this theme do have them.' ),
736 'reorderModeOn' => __( 'Reorder mode enabled' ),
737 'reorderModeOff' => __( 'Reorder mode closed' ),
738 'reorderLabelOn' => esc_attr__( 'Reorder widgets' ),
739 'widgetsFound' => __( 'Number of widgets found: %d' ),
740 'noWidgetsFound' => __( 'No widgets found.' ),
743 'widgetReorderNav' => $widget_reorder_nav_tpl,
744 'moveWidgetArea' => $move_widget_area_tpl,
746 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
749 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
750 unset( $registered_widget['callback'] ); // may not be JSON-serializeable
753 $wp_scripts->add_data(
756 sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
761 * Renders the widget form control templates into the DOM.
766 public function output_widget_control_templates() {
768 <div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
769 <div id="available-widgets">
770 <div class="customize-section-title">
771 <button class="customize-section-back" tabindex="-1">
772 <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
775 <span class="customize-action"><?php
776 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
777 echo sprintf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'widgets' )->title ) );
779 <?php _e( 'Add a Widget' ); ?>
782 <div id="available-widgets-filter">
783 <label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
784 <input type="text" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets…' ) ?>" aria-describedby="widgets-search-desc" />
785 <div class="search-icon" aria-hidden="true"></div>
786 <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
787 <p class="screen-reader-text" id="widgets-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
789 <div id="available-widgets-list">
790 <?php foreach ( $this->get_available_widgets() as $available_widget ): ?>
791 <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">
792 <?php echo $available_widget['control_tpl']; ?>
795 <p class="no-widgets-found-message"><?php _e( 'No widgets found.' ); ?></p>
796 </div><!-- #available-widgets-list -->
797 </div><!-- #available-widgets -->
798 </div><!-- #widgets-left -->
803 * Calls admin_print_footer_scripts and admin_print_scripts hooks to
804 * allow custom scripts from plugins.
809 public function print_footer_scripts() {
810 /** This action is documented in wp-admin/admin-footer.php */
811 do_action( 'admin_print_footer_scripts-widgets.php' );
813 /** This action is documented in wp-admin/admin-footer.php */
814 do_action( 'admin_print_footer_scripts' );
816 /** This action is documented in wp-admin/admin-footer.php */
817 do_action( 'admin_footer-widgets.php' );
821 * Retrieves common arguments to supply when constructing a Customizer setting.
826 * @param string $id Widget setting ID.
827 * @param array $overrides Array of setting overrides.
828 * @return array Possibly modified setting arguments.
830 public function get_setting_args( $id, $overrides = array() ) {
833 'capability' => 'edit_theme_options',
834 'default' => array(),
837 if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
838 $args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
839 $args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
840 $args['transport'] = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
841 } elseif ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
842 $args['sanitize_callback'] = array( $this, 'sanitize_widget_instance' );
843 $args['sanitize_js_callback'] = array( $this, 'sanitize_widget_js_instance' );
844 $args['transport'] = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
847 $args = array_merge( $args, $overrides );
850 * Filters the common arguments supplied when constructing a Customizer setting.
854 * @see WP_Customize_Setting
856 * @param array $args Array of Customizer setting arguments.
857 * @param string $id Widget setting ID.
859 return apply_filters( 'widget_customizer_setting_args', $args, $id );
863 * Ensures sidebar widget arrays only ever contain widget IDS.
865 * Used as the 'sanitize_callback' for each $sidebars_widgets setting.
870 * @param array $widget_ids Array of widget IDs.
871 * @return array Array of sanitized widget IDs.
873 public function sanitize_sidebar_widgets( $widget_ids ) {
874 $widget_ids = array_map( 'strval', (array) $widget_ids );
875 $sanitized_widget_ids = array();
876 foreach ( $widget_ids as $widget_id ) {
877 $sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
879 return $sanitized_widget_ids;
883 * Builds up an index of all available widgets for use in Backbone models.
888 * @global array $wp_registered_widgets
889 * @global array $wp_registered_widget_controls
890 * @staticvar array $available_widgets
892 * @see wp_list_widgets()
894 * @return array List of available widgets.
896 public function get_available_widgets() {
897 static $available_widgets = array();
898 if ( ! empty( $available_widgets ) ) {
899 return $available_widgets;
902 global $wp_registered_widgets, $wp_registered_widget_controls;
903 require_once ABSPATH . '/wp-admin/includes/widgets.php'; // for next_widget_id_number()
905 $sort = $wp_registered_widgets;
906 usort( $sort, array( $this, '_sort_name_callback' ) );
909 foreach ( $sort as $widget ) {
910 if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget
914 $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
915 $done[] = $widget['callback'];
917 if ( ! isset( $widget['params'][0] ) ) {
918 $widget['params'][0] = array();
921 $available_widget = $widget;
922 unset( $available_widget['callback'] ); // not serializable to JSON
925 'widget_id' => $widget['id'],
926 'widget_name' => $widget['name'],
927 '_display' => 'template',
930 $is_disabled = false;
931 $is_multi_widget = ( isset( $wp_registered_widget_controls[$widget['id']]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
932 if ( $is_multi_widget ) {
933 $id_base = $wp_registered_widget_controls[$widget['id']]['id_base'];
934 $args['_temp_id'] = "$id_base-__i__";
935 $args['_multi_num'] = next_widget_id_number( $id_base );
936 $args['_add'] = 'multi';
938 $args['_add'] = 'single';
940 if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
943 $id_base = $widget['id'];
946 $list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar( array( 0 => $args, 1 => $widget['params'][0] ) );
947 $control_tpl = $this->get_widget_control( $list_widget_controls_args );
949 // The properties here are mapped to the Backbone Widget model.
950 $available_widget = array_merge( $available_widget, array(
951 'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
952 'is_multi' => $is_multi_widget,
953 'control_tpl' => $control_tpl,
954 'multi_number' => ( $args['_add'] === 'multi' ) ? $args['_multi_num'] : false,
955 'is_disabled' => $is_disabled,
956 'id_base' => $id_base,
957 'transport' => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
958 'width' => $wp_registered_widget_controls[$widget['id']]['width'],
959 'height' => $wp_registered_widget_controls[$widget['id']]['height'],
960 'is_wide' => $this->is_wide_widget( $widget['id'] ),
963 $available_widgets[] = $available_widget;
966 return $available_widgets;
970 * Naturally orders available widgets by name.
975 * @param array $widget_a The first widget to compare.
976 * @param array $widget_b The second widget to compare.
977 * @return int Reorder position for the current widget comparison.
979 protected function _sort_name_callback( $widget_a, $widget_b ) {
980 return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
984 * Retrieves the widget control markup.
989 * @param array $args Widget control arguments.
990 * @return string Widget control form HTML markup.
992 public function get_widget_control( $args ) {
993 $args[0]['before_form'] = '<div class="form">';
994 $args[0]['after_form'] = '</div><!-- .form -->';
995 $args[0]['before_widget_content'] = '<div class="widget-content">';
996 $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
998 call_user_func_array( 'wp_widget_control', $args );
999 $control_tpl = ob_get_clean();
1000 return $control_tpl;
1004 * Retrieves the widget control markup parts.
1009 * @param array $args Widget control arguments.
1011 * @type string $control Markup for widget control wrapping form.
1012 * @type string $content The contents of the widget form itself.
1015 public function get_widget_control_parts( $args ) {
1016 $args[0]['before_widget_content'] = '<div class="widget-content">';
1017 $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
1018 $control_markup = $this->get_widget_control( $args );
1020 $content_start_pos = strpos( $control_markup, $args[0]['before_widget_content'] );
1021 $content_end_pos = strrpos( $control_markup, $args[0]['after_widget_content'] );
1023 $control = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
1024 $control .= substr( $control_markup, $content_end_pos );
1025 $content = trim( substr(
1027 $content_start_pos + strlen( $args[0]['before_widget_content'] ),
1028 $content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
1031 return compact( 'control', 'content' );
1035 * Adds hooks for the Customizer preview.
1040 public function customize_preview_init() {
1041 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
1042 add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
1043 add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
1047 * Refreshes the nonce for widget updates.
1052 * @param array $nonces Array of nonces.
1053 * @return array $nonces Array of nonces.
1055 public function refresh_nonces( $nonces ) {
1056 $nonces['update-widget'] = wp_create_nonce( 'update-widget' );
1061 * When previewing, ensures the proper previewing widgets are used.
1063 * Because wp_get_sidebars_widgets() gets called early at {@see 'init' } (via
1064 * wp_convert_widget_settings()) and can set global variable `$_wp_sidebars_widgets`
1065 * to the value of `get_option( 'sidebars_widgets' )` before the Customizer preview
1066 * filter is added, it has to be reset after the filter has been added.
1071 * @param array $sidebars_widgets List of widgets for the current sidebar.
1074 public function preview_sidebars_widgets( $sidebars_widgets ) {
1075 $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1077 unset( $sidebars_widgets['array_version'] );
1078 return $sidebars_widgets;
1082 * Enqueues scripts for the Customizer preview.
1087 public function customize_preview_enqueue() {
1088 wp_enqueue_script( 'customize-preview-widgets' );
1089 wp_enqueue_style( 'customize-preview' );
1093 * Inserts default style for highlighted widget at early point so theme
1094 * stylesheet can override.
1099 public function print_preview_css() {
1102 .widget-customizer-highlighted-widget {
1104 -webkit-box-shadow: 0 0 2px rgba(30,140,190,0.8);
1105 box-shadow: 0 0 2px rgba(30,140,190,0.8);
1114 * Communicates the sidebars that appeared on the page at the very end of the page,
1115 * and at the very end of the wp_footer,
1120 * @global array $wp_registered_sidebars
1121 * @global array $wp_registered_widgets
1123 public function export_preview_data() {
1124 global $wp_registered_sidebars, $wp_registered_widgets;
1126 $switched_locale = switch_to_locale( get_user_locale() );
1128 'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
1130 if ( $switched_locale ) {
1131 restore_previous_locale();
1134 // Prepare Customizer settings to pass to JavaScript.
1136 'renderedSidebars' => array_fill_keys( array_unique( $this->rendered_sidebars ), true ),
1137 'renderedWidgets' => array_fill_keys( array_keys( $this->rendered_widgets ), true ),
1138 'registeredSidebars' => array_values( $wp_registered_sidebars ),
1139 'registeredWidgets' => $wp_registered_widgets,
1141 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
1143 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
1144 unset( $registered_widget['callback'] ); // may not be JSON-serializeable
1148 <script type="text/javascript">
1149 var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
1155 * Tracks the widgets that were rendered.
1160 * @param array $widget Rendered widget to tally.
1162 public function tally_rendered_widgets( $widget ) {
1163 $this->rendered_widgets[ $widget['id'] ] = true;
1167 * Determine if a widget is rendered on the page.
1172 * @param string $widget_id Widget ID to check.
1173 * @return bool Whether the widget is rendered.
1175 public function is_widget_rendered( $widget_id ) {
1176 return in_array( $widget_id, $this->rendered_widgets );
1180 * Determines if a sidebar is rendered on the page.
1185 * @param string $sidebar_id Sidebar ID to check.
1186 * @return bool Whether the sidebar is rendered.
1188 public function is_sidebar_rendered( $sidebar_id ) {
1189 return in_array( $sidebar_id, $this->rendered_sidebars );
1193 * Tallies the sidebars rendered via is_active_sidebar().
1195 * Keep track of the times that is_active_sidebar() is called in the template,
1196 * and assume that this means that the sidebar would be rendered on the template
1197 * if there were widgets populating it.
1202 * @param bool $is_active Whether the sidebar is active.
1203 * @param string $sidebar_id Sidebar ID.
1204 * @return bool Whether the sidebar is active.
1206 public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
1207 if ( is_registered_sidebar( $sidebar_id ) ) {
1208 $this->rendered_sidebars[] = $sidebar_id;
1211 * We may need to force this to true, and also force-true the value
1212 * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
1213 * is an area to drop widgets into, if the sidebar is empty.
1219 * Tallies the sidebars rendered via dynamic_sidebar().
1221 * Keep track of the times that dynamic_sidebar() is called in the template,
1222 * and assume this means the sidebar would be rendered on the template if
1223 * there were widgets populating it.
1228 * @param bool $has_widgets Whether the current sidebar has widgets.
1229 * @param string $sidebar_id Sidebar ID.
1230 * @return bool Whether the current sidebar has widgets.
1232 public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
1233 if ( is_registered_sidebar( $sidebar_id ) ) {
1234 $this->rendered_sidebars[] = $sidebar_id;
1238 * We may need to force this to true, and also force-true the value
1239 * for 'is_active_sidebar' if we want to ensure there is an area to
1240 * drop widgets into, if the sidebar is empty.
1242 return $has_widgets;
1246 * Retrieves MAC for a serialized widget instance string.
1248 * Allows values posted back from JS to be rejected if any tampering of the
1249 * data has occurred.
1254 * @param string $serialized_instance Widget instance.
1255 * @return string MAC for serialized widget instance.
1257 protected function get_instance_hash_key( $serialized_instance ) {
1258 return wp_hash( $serialized_instance );
1262 * Sanitizes a widget instance.
1264 * Unserialize the JS-instance for storing in the options. It's important that this filter
1265 * only get applied to an instance *once*.
1270 * @param array $value Widget instance to sanitize.
1271 * @return array|void Sanitized widget instance.
1273 public function sanitize_widget_instance( $value ) {
1274 if ( $value === array() ) {
1278 if ( empty( $value['is_widget_customizer_js_value'] )
1279 || empty( $value['instance_hash_key'] )
1280 || empty( $value['encoded_serialized_instance'] ) )
1285 $decoded = base64_decode( $value['encoded_serialized_instance'], true );
1286 if ( false === $decoded ) {
1290 if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
1294 $instance = unserialize( $decoded );
1295 if ( false === $instance ) {
1303 * Converts a widget instance into JSON-representable format.
1308 * @param array $value Widget instance to convert to JSON.
1309 * @return array JSON-converted widget instance.
1311 public function sanitize_widget_js_instance( $value ) {
1312 if ( empty( $value['is_widget_customizer_js_value'] ) ) {
1313 $serialized = serialize( $value );
1316 'encoded_serialized_instance' => base64_encode( $serialized ),
1317 'title' => empty( $value['title'] ) ? '' : $value['title'],
1318 'is_widget_customizer_js_value' => true,
1319 'instance_hash_key' => $this->get_instance_hash_key( $serialized ),
1326 * Strips out widget IDs for widgets which are no longer registered.
1328 * One example where this might happen is when a plugin orphans a widget
1329 * in a sidebar upon deactivation.
1334 * @global array $wp_registered_widgets
1336 * @param array $widget_ids List of widget IDs.
1337 * @return array Parsed list of widget IDs.
1339 public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
1340 global $wp_registered_widgets;
1341 $widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
1346 * Finds and invokes the widget update and control callbacks.
1348 * Requires that `$_POST` be populated with the instance data.
1353 * @global array $wp_registered_widget_updates
1354 * @global array $wp_registered_widget_controls
1356 * @param string $widget_id Widget ID.
1357 * @return WP_Error|array Array containing the updated widget information.
1358 * A WP_Error object, otherwise.
1360 public function call_widget_update( $widget_id ) {
1361 global $wp_registered_widget_updates, $wp_registered_widget_controls;
1363 $setting_id = $this->get_setting_id( $widget_id );
1366 * Make sure that other setting changes have previewed since this widget
1367 * may depend on them (e.g. Menus being present for Custom Menu widget).
1369 if ( ! did_action( 'customize_preview_init' ) ) {
1370 foreach ( $this->manager->settings() as $setting ) {
1371 if ( $setting->id !== $setting_id ) {
1372 $setting->preview();
1377 $this->start_capturing_option_updates();
1378 $parsed_id = $this->parse_widget_id( $widget_id );
1379 $option_name = 'widget_' . $parsed_id['id_base'];
1382 * If a previously-sanitized instance is provided, populate the input vars
1383 * with its values so that the widget update callback will read this instance
1385 $added_input_vars = array();
1386 if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
1387 $sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
1388 if ( false === $sanitized_widget_setting ) {
1389 $this->stop_capturing_option_updates();
1390 return new WP_Error( 'widget_setting_malformed' );
1393 $instance = $this->sanitize_widget_instance( $sanitized_widget_setting );
1394 if ( is_null( $instance ) ) {
1395 $this->stop_capturing_option_updates();
1396 return new WP_Error( 'widget_setting_unsanitized' );
1399 if ( ! is_null( $parsed_id['number'] ) ) {
1401 $value[$parsed_id['number']] = $instance;
1402 $key = 'widget-' . $parsed_id['id_base'];
1403 $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1404 $added_input_vars[] = $key;
1406 foreach ( $instance as $key => $value ) {
1407 $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1408 $added_input_vars[] = $key;
1413 // Invoke the widget update callback.
1414 foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
1415 if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
1417 call_user_func_array( $control['callback'], $control['params'] );
1423 // Clean up any input vars that were manually added
1424 foreach ( $added_input_vars as $key ) {
1425 unset( $_POST[ $key ] );
1426 unset( $_REQUEST[ $key ] );
1429 // Make sure the expected option was updated.
1430 if ( 0 !== $this->count_captured_options() ) {
1431 if ( $this->count_captured_options() > 1 ) {
1432 $this->stop_capturing_option_updates();
1433 return new WP_Error( 'widget_setting_too_many_options' );
1436 $updated_option_name = key( $this->get_captured_options() );
1437 if ( $updated_option_name !== $option_name ) {
1438 $this->stop_capturing_option_updates();
1439 return new WP_Error( 'widget_setting_unexpected_option' );
1443 // Obtain the widget instance.
1444 $option = $this->get_captured_option( $option_name );
1445 if ( null !== $parsed_id['number'] ) {
1446 $instance = $option[ $parsed_id['number'] ];
1448 $instance = $option;
1452 * Override the incoming $_POST['customized'] for a newly-created widget's
1453 * setting with the new $instance so that the preview filter currently
1454 * in place from WP_Customize_Setting::preview() will use this value
1455 * instead of the default widget instance value (an empty array).
1457 $this->manager->set_post_value( $setting_id, $this->sanitize_widget_js_instance( $instance ) );
1459 // Obtain the widget control with the updated instance in place.
1461 $form = $wp_registered_widget_controls[ $widget_id ];
1463 call_user_func_array( $form['callback'], $form['params'] );
1465 $form = ob_get_clean();
1467 $this->stop_capturing_option_updates();
1469 return compact( 'instance', 'form' );
1473 * Updates widget settings asynchronously.
1475 * Allows the Customizer to update a widget using its form, but return the new
1476 * instance info via Ajax instead of saving it to the options table.
1478 * Most code here copied from wp_ajax_save_widget().
1483 * @see wp_ajax_save_widget()
1485 public function wp_ajax_update_widget() {
1487 if ( ! is_user_logged_in() ) {
1491 check_ajax_referer( 'update-widget', 'nonce' );
1493 if ( ! current_user_can( 'edit_theme_options' ) ) {
1497 if ( empty( $_POST['widget-id'] ) ) {
1498 wp_send_json_error( 'missing_widget-id' );
1501 /** This action is documented in wp-admin/includes/ajax-actions.php */
1502 do_action( 'load-widgets.php' );
1504 /** This action is documented in wp-admin/includes/ajax-actions.php */
1505 do_action( 'widgets.php' );
1507 /** This action is documented in wp-admin/widgets.php */
1508 do_action( 'sidebar_admin_setup' );
1510 $widget_id = $this->get_post_value( 'widget-id' );
1511 $parsed_id = $this->parse_widget_id( $widget_id );
1512 $id_base = $parsed_id['id_base'];
1514 $is_updating_widget_template = (
1515 isset( $_POST[ 'widget-' . $id_base ] )
1517 is_array( $_POST[ 'widget-' . $id_base ] )
1519 preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
1521 if ( $is_updating_widget_template ) {
1522 wp_send_json_error( 'template_widget_not_updatable' );
1525 $updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
1526 if ( is_wp_error( $updated_widget ) ) {
1527 wp_send_json_error( $updated_widget->get_error_code() );
1530 $form = $updated_widget['form'];
1531 $instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );
1533 wp_send_json_success( compact( 'form', 'instance' ) );
1537 * Selective Refresh Methods
1541 * Filters arguments for dynamic widget partials.
1546 * @param array|false $partial_args Partial arguments.
1547 * @param string $partial_id Partial ID.
1548 * @return array (Maybe) modified partial arguments.
1550 public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1551 if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
1552 return $partial_args;
1555 if ( preg_match( '/^widget\[(?P<widget_id>.+)\]$/', $partial_id, $matches ) ) {
1556 if ( false === $partial_args ) {
1557 $partial_args = array();
1559 $partial_args = array_merge(
1563 'render_callback' => array( $this, 'render_widget_partial' ),
1564 'container_inclusive' => true,
1565 'settings' => array( $this->get_setting_id( $matches['widget_id'] ) ),
1566 'capability' => 'edit_theme_options',
1571 return $partial_args;
1575 * Adds hooks for selective refresh.
1580 public function selective_refresh_init() {
1581 if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
1584 add_filter( 'dynamic_sidebar_params', array( $this, 'filter_dynamic_sidebar_params' ) );
1585 add_filter( 'wp_kses_allowed_html', array( $this, 'filter_wp_kses_allowed_data_attributes' ) );
1586 add_action( 'dynamic_sidebar_before', array( $this, 'start_dynamic_sidebar' ) );
1587 add_action( 'dynamic_sidebar_after', array( $this, 'end_dynamic_sidebar' ) );
1591 * Inject selective refresh data attributes into widget container elements.
1593 * @param array $params {
1594 * Dynamic sidebar params.
1596 * @type array $args Sidebar args.
1597 * @type array $widget_args Widget args.
1599 * @see WP_Customize_Nav_Menus_Partial_Refresh::filter_wp_nav_menu_args()
1601 * @return array Params.
1603 public function filter_dynamic_sidebar_params( $params ) {
1604 $sidebar_args = array_merge(
1606 'before_widget' => '',
1607 'after_widget' => '',
1612 // Skip widgets not in a registered sidebar or ones which lack a proper wrapper element to attach the data-* attributes to.
1615 isset( $sidebar_args['id'] )
1617 is_registered_sidebar( $sidebar_args['id'] )
1619 ( isset( $this->current_dynamic_sidebar_id_stack[0] ) && $this->current_dynamic_sidebar_id_stack[0] === $sidebar_args['id'] )
1621 preg_match( '#^<(?P<tag_name>\w+)#', $sidebar_args['before_widget'], $matches )
1623 if ( ! $is_valid ) {
1626 $this->before_widget_tags_seen[ $matches['tag_name'] ] = true;
1629 'sidebar_id' => $sidebar_args['id'],
1631 if ( isset( $this->context_sidebar_instance_number ) ) {
1632 $context['sidebar_instance_number'] = $this->context_sidebar_instance_number;
1633 } else if ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
1634 $context['sidebar_instance_number'] = $this->sidebar_instance_count[ $sidebar_args['id'] ];
1637 $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
1638 $attributes .= ' data-customize-partial-type="widget"';
1639 $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
1640 $attributes .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
1641 $sidebar_args['before_widget'] = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $sidebar_args['before_widget'] );
1643 $params[0] = $sidebar_args;
1648 * List of the tag names seen for before_widget strings.
1650 * This is used in the {@see 'filter_wp_kses_allowed_html'} filter to ensure that the
1651 * data-* attributes can be whitelisted.
1657 protected $before_widget_tags_seen = array();
1660 * Ensures the HTML data-* attributes for selective refresh are allowed by kses.
1662 * This is needed in case the `$before_widget` is run through wp_kses() when printed.
1667 * @param array $allowed_html Allowed HTML.
1668 * @return array (Maybe) modified allowed HTML.
1670 public function filter_wp_kses_allowed_data_attributes( $allowed_html ) {
1671 foreach ( array_keys( $this->before_widget_tags_seen ) as $tag_name ) {
1672 if ( ! isset( $allowed_html[ $tag_name ] ) ) {
1673 $allowed_html[ $tag_name ] = array();
1675 $allowed_html[ $tag_name ] = array_merge(
1676 $allowed_html[ $tag_name ],
1677 array_fill_keys( array(
1678 'data-customize-partial-id',
1679 'data-customize-partial-type',
1680 'data-customize-partial-placement-context',
1681 'data-customize-partial-widget-id',
1682 'data-customize-partial-options',
1686 return $allowed_html;
1690 * Keep track of the number of times that dynamic_sidebar() was called for a given sidebar index.
1692 * This helps facilitate the uncommon scenario where a single sidebar is rendered multiple times on a template.
1698 protected $sidebar_instance_count = array();
1701 * The current request's sidebar_instance_number context.
1707 protected $context_sidebar_instance_number;
1710 * Current sidebar ID being rendered.
1716 protected $current_dynamic_sidebar_id_stack = array();
1719 * Begins keeping track of the current sidebar being rendered.
1721 * Insert marker before widgets are rendered in a dynamic sidebar.
1726 * @param int|string $index Index, name, or ID of the dynamic sidebar.
1728 public function start_dynamic_sidebar( $index ) {
1729 array_unshift( $this->current_dynamic_sidebar_id_stack, $index );
1730 if ( ! isset( $this->sidebar_instance_count[ $index ] ) ) {
1731 $this->sidebar_instance_count[ $index ] = 0;
1733 $this->sidebar_instance_count[ $index ] += 1;
1734 if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
1735 printf( "\n<!--dynamic_sidebar_before:%s:%d-->\n", esc_html( $index ), intval( $this->sidebar_instance_count[ $index ] ) );
1740 * Finishes keeping track of the current sidebar being rendered.
1742 * Inserts a marker after widgets are rendered in a dynamic sidebar.
1747 * @param int|string $index Index, name, or ID of the dynamic sidebar.
1749 public function end_dynamic_sidebar( $index ) {
1750 array_shift( $this->current_dynamic_sidebar_id_stack );
1751 if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
1752 printf( "\n<!--dynamic_sidebar_after:%s:%d-->\n", esc_html( $index ), intval( $this->sidebar_instance_count[ $index ] ) );
1757 * Current sidebar being rendered.
1763 protected $rendering_widget_id;
1766 * Current widget being rendered.
1772 protected $rendering_sidebar_id;
1775 * Filters sidebars_widgets to ensure the currently-rendered widget is the only widget in the current sidebar.
1780 * @param array $sidebars_widgets Sidebars widgets.
1781 * @return array Filtered sidebars widgets.
1783 public function filter_sidebars_widgets_for_rendering_widget( $sidebars_widgets ) {
1784 $sidebars_widgets[ $this->rendering_sidebar_id ] = array( $this->rendering_widget_id );
1785 return $sidebars_widgets;
1789 * Renders a specific widget using the supplied sidebar arguments.
1794 * @see dynamic_sidebar()
1796 * @param WP_Customize_Partial $partial Partial.
1797 * @param array $context {
1798 * Sidebar args supplied as container context.
1800 * @type string $sidebar_id ID for sidebar for widget to render into.
1801 * @type int $sidebar_instance_number Disambiguating instance number.
1803 * @return string|false
1805 public function render_widget_partial( $partial, $context ) {
1806 $id_data = $partial->id_data();
1807 $widget_id = array_shift( $id_data['keys'] );
1809 if ( ! is_array( $context )
1810 || empty( $context['sidebar_id'] )
1811 || ! is_registered_sidebar( $context['sidebar_id'] )
1816 $this->rendering_sidebar_id = $context['sidebar_id'];
1818 if ( isset( $context['sidebar_instance_number'] ) ) {
1819 $this->context_sidebar_instance_number = intval( $context['sidebar_instance_number'] );
1822 // Filter sidebars_widgets so that only the queried widget is in the sidebar.
1823 $this->rendering_widget_id = $widget_id;
1825 $filter_callback = array( $this, 'filter_sidebars_widgets_for_rendering_widget' );
1826 add_filter( 'sidebars_widgets', $filter_callback, 1000 );
1828 // Render the widget.
1830 dynamic_sidebar( $this->rendering_sidebar_id = $context['sidebar_id'] );
1831 $container = ob_get_clean();
1833 // Reset variables for next partial render.
1834 remove_filter( 'sidebars_widgets', $filter_callback, 1000 );
1836 $this->context_sidebar_instance_number = null;
1837 $this->rendering_sidebar_id = null;
1838 $this->rendering_widget_id = null;
1844 // Option Update Capturing
1848 * List of captured widget option updates.
1852 * @var array $_captured_options Values updated while option capture is happening.
1854 protected $_captured_options = array();
1857 * Whether option capture is currently happening.
1861 * @var bool $_is_current Whether option capture is currently happening or not.
1863 protected $_is_capturing_option_updates = false;
1866 * Determines whether the captured option update should be ignored.
1871 * @param string $option_name Option name.
1872 * @return bool Whether the option capture is ignored.
1874 protected function is_option_capture_ignored( $option_name ) {
1875 return ( 0 === strpos( $option_name, '_transient_' ) );
1879 * Retrieves captured widget option updates.
1884 * @return array Array of captured options.
1886 protected function get_captured_options() {
1887 return $this->_captured_options;
1891 * Retrieves the option that was captured from being saved.
1896 * @param string $option_name Option name.
1897 * @param mixed $default Optional. Default value to return if the option does not exist. Default false.
1898 * @return mixed Value set for the option.
1900 protected function get_captured_option( $option_name, $default = false ) {
1901 if ( array_key_exists( $option_name, $this->_captured_options ) ) {
1902 $value = $this->_captured_options[ $option_name ];
1910 * Retrieves the number of captured widget option updates.
1915 * @return int Number of updated options.
1917 protected function count_captured_options() {
1918 return count( $this->_captured_options );
1922 * Begins keeping track of changes to widget options, caching new values.
1927 protected function start_capturing_option_updates() {
1928 if ( $this->_is_capturing_option_updates ) {
1932 $this->_is_capturing_option_updates = true;
1934 add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
1938 * Pre-filters captured option values before updating.
1943 * @param mixed $new_value The new option value.
1944 * @param string $option_name Name of the option.
1945 * @param mixed $old_value The old option value.
1946 * @return mixed Filtered option value.
1948 public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
1949 if ( $this->is_option_capture_ignored( $option_name ) ) {
1953 if ( ! isset( $this->_captured_options[ $option_name ] ) ) {
1954 add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1957 $this->_captured_options[ $option_name ] = $new_value;
1963 * Pre-filters captured option values before retrieving.
1968 * @param mixed $value Value to return instead of the option value.
1969 * @return mixed Filtered option value.
1971 public function capture_filter_pre_get_option( $value ) {
1972 $option_name = preg_replace( '/^pre_option_/', '', current_filter() );
1974 if ( isset( $this->_captured_options[ $option_name ] ) ) {
1975 $value = $this->_captured_options[ $option_name ];
1977 /** This filter is documented in wp-includes/option.php */
1978 $value = apply_filters( 'option_' . $option_name, $value );
1985 * Undoes any changes to the options since options capture began.
1990 protected function stop_capturing_option_updates() {
1991 if ( ! $this->_is_capturing_option_updates ) {
1995 remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10 );
1997 foreach ( array_keys( $this->_captured_options ) as $option_name ) {
1998 remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
2001 $this->_captured_options = array();
2002 $this->_is_capturing_option_updates = false;
2006 * {@internal Missing Summary}
2008 * See the {@see 'customize_dynamic_setting_args'} filter.
2011 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2013 public function setup_widget_addition_previews() {
2014 _deprecated_function( __METHOD__, '4.2.0' );
2018 * {@internal Missing Summary}
2020 * See the {@see 'customize_dynamic_setting_args'} filter.
2023 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2025 public function prepreview_added_sidebars_widgets() {
2026 _deprecated_function( __METHOD__, '4.2.0' );
2030 * {@internal Missing Summary}
2032 * See the {@see 'customize_dynamic_setting_args'} filter.
2035 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2037 public function prepreview_added_widget_instance() {
2038 _deprecated_function( __METHOD__, '4.2.0' );
2042 * {@internal Missing Summary}
2044 * See the {@see 'customize_dynamic_setting_args'} filter.
2047 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
2049 public function remove_prepreview_filters() {
2050 _deprecated_function( __METHOD__, '4.2.0' );