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 setting type to setting ID pattern.
71 protected $setting_id_patterns = array(
72 'widget_instance' => '/^(widget_.+?)(?:\[(\d+)\])?$/',
73 'sidebar_widgets' => '/^sidebars_widgets\[(.+?)\]$/',
82 * @param WP_Customize_Manager $manager Customize manager bootstrap instance.
84 public function __construct( $manager ) {
85 $this->manager = $manager;
87 add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
88 add_action( 'after_setup_theme', array( $this, 'register_settings' ) );
89 add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
90 add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
91 add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
92 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
93 add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
94 add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
95 add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
96 add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
97 add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
98 add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
100 add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
101 add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
102 add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
106 * Get the widget setting type given a setting ID.
111 * @param $setting_id Setting ID.
112 * @return string|null Setting type. Null otherwise.
114 protected function get_setting_type( $setting_id ) {
115 static $cache = array();
116 if ( isset( $cache[ $setting_id ] ) ) {
117 return $cache[ $setting_id ];
119 foreach ( $this->setting_id_patterns as $type => $pattern ) {
120 if ( preg_match( $pattern, $setting_id ) ) {
121 $cache[ $setting_id ] = $type;
129 * Inspect the incoming customized data for any widget settings, and dynamically add them up-front so widgets will be initialized properly.
134 public function register_settings() {
135 $widget_setting_ids = array();
136 $incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
137 foreach ( $incoming_setting_ids as $setting_id ) {
138 if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
139 $widget_setting_ids[] = $setting_id;
142 if ( $this->manager->doing_ajax( 'update-widget' ) && isset( $_REQUEST['widget-id'] ) ) {
143 $widget_setting_ids[] = $this->get_setting_id( wp_unslash( $_REQUEST['widget-id'] ) );
146 $settings = $this->manager->add_dynamic_settings( array_unique( $widget_setting_ids ) );
149 * Preview settings right away so that widgets and sidebars will get registered properly.
150 * But don't do this if a customize_save because this will cause WP to think there is nothing
151 * changed that needs to be saved.
153 if ( ! $this->manager->doing_ajax( 'customize_save' ) ) {
154 foreach ( $settings as $setting ) {
161 * Determine the arguments for a dynamically-created setting.
166 * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
167 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
168 * @return false|array Setting arguments, false otherwise.
170 public function filter_customize_dynamic_setting_args( $args, $setting_id ) {
171 if ( $this->get_setting_type( $setting_id ) ) {
172 $args = $this->get_setting_args( $setting_id );
178 * Get an unslashed post value or return a default.
184 * @param string $name Post value.
185 * @param mixed $default Default post value.
186 * @return mixed Unslashed post value or default value.
188 protected function get_post_value( $name, $default = null ) {
189 if ( ! isset( $_POST[ $name ] ) ) {
193 return wp_unslash( $_POST[ $name ] );
197 * Override sidebars_widgets for theme switch.
199 * When switching a theme via the Customizer, supply any previously-configured
200 * sidebars_widgets from the target theme as the initial sidebars_widgets
201 * setting. Also store the old theme's existing settings so that they can
202 * be passed along for storing in the sidebars_widgets theme_mod when the
203 * theme gets switched.
208 public function override_sidebars_widgets_for_theme_switch() {
209 global $sidebars_widgets;
211 if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
215 $this->old_sidebars_widgets = wp_get_sidebars_widgets();
216 add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
218 // retrieve_widgets() looks at the global $sidebars_widgets
219 $sidebars_widgets = $this->old_sidebars_widgets;
220 $sidebars_widgets = retrieve_widgets( 'customize' );
221 add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
222 unset( $GLOBALS['_wp_sidebars_widgets'] ); // reset global cache var used by wp_get_sidebars_widgets()
226 * Filter old_sidebars_widgets_data Customizer setting.
228 * When switching themes, filter the Customizer setting
229 * old_sidebars_widgets_data to supply initial $sidebars_widgets before they
230 * were overridden by retrieve_widgets(). The value for
231 * old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
234 * @see WP_Customize_Widgets::handle_theme_switch()
238 * @param array $old_sidebars_widgets
240 public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
241 return $this->old_sidebars_widgets;
245 * Filter sidebars_widgets option for theme switch.
247 * When switching themes, the retrieve_widgets() function is run when the
248 * Customizer initializes, and then the new sidebars_widgets here get
249 * supplied as the default value for the sidebars_widgets option.
251 * @see WP_Customize_Widgets::handle_theme_switch()
255 * @param array $sidebars_widgets
257 public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
258 $sidebars_widgets = $GLOBALS['sidebars_widgets'];
259 $sidebars_widgets['array_version'] = 3;
260 return $sidebars_widgets;
264 * Make sure all widgets get loaded into the Customizer.
266 * Note: these actions are also fired in wp_ajax_update_widget().
271 public function customize_controls_init() {
272 /** This action is documented in wp-admin/includes/ajax-actions.php */
273 do_action( 'load-widgets.php' );
275 /** This action is documented in wp-admin/includes/ajax-actions.php */
276 do_action( 'widgets.php' );
278 /** This action is documented in wp-admin/widgets.php */
279 do_action( 'sidebar_admin_setup' );
283 * Ensure widgets are available for all types of previews.
285 * When in preview, hook to 'customize_register' for settings
286 * after WordPress is loaded so that all filters have been
287 * initialized (e.g. Widget Visibility).
292 public function schedule_customize_register() {
294 $this->customize_register();
296 add_action( 'wp', array( $this, 'customize_register' ) );
301 * Register Customizer settings and controls for all sidebars and widgets.
306 public function customize_register() {
307 global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
309 $sidebars_widgets = array_merge(
310 array( 'wp_inactive_widgets' => array() ),
311 array_fill_keys( array_keys( $GLOBALS['wp_registered_sidebars'] ), array() ),
312 wp_get_sidebars_widgets()
315 $new_setting_ids = array();
318 * Register a setting for all widgets, including those which are active,
319 * inactive, and orphaned since a widget may get suppressed from a sidebar
320 * via a plugin (like Widget Visibility).
322 foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
323 $setting_id = $this->get_setting_id( $widget_id );
324 $setting_args = $this->get_setting_args( $setting_id );
325 if ( ! $this->manager->get_setting( $setting_id ) ) {
326 $this->manager->add_setting( $setting_id, $setting_args );
328 $new_setting_ids[] = $setting_id;
332 * Add a setting which will be supplied for the theme's sidebars_widgets
333 * theme_mod when the the theme is switched.
335 if ( ! $this->manager->is_theme_active() ) {
336 $setting_id = 'old_sidebars_widgets_data';
337 $setting_args = $this->get_setting_args( $setting_id, array(
338 'type' => 'global_variable',
341 $this->manager->add_setting( $setting_id, $setting_args );
344 $this->manager->add_panel( 'widgets', array(
345 'title' => __( 'Widgets' ),
346 'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
350 foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
351 if ( empty( $sidebar_widget_ids ) ) {
352 $sidebar_widget_ids = array();
355 $is_registered_sidebar = isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] );
356 $is_inactive_widgets = ( 'wp_inactive_widgets' === $sidebar_id );
357 $is_active_sidebar = ( $is_registered_sidebar && ! $is_inactive_widgets );
359 // Add setting for managing the sidebar's widgets.
360 if ( $is_registered_sidebar || $is_inactive_widgets ) {
361 $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
362 $setting_args = $this->get_setting_args( $setting_id );
363 if ( ! $this->manager->get_setting( $setting_id ) ) {
364 if ( ! $this->manager->is_theme_active() ) {
365 $setting_args['dirty'] = true;
367 $this->manager->add_setting( $setting_id, $setting_args );
369 $new_setting_ids[] = $setting_id;
371 // Add section to contain controls.
372 $section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
373 if ( $is_active_sidebar ) {
375 $section_args = array(
376 'title' => $GLOBALS['wp_registered_sidebars'][ $sidebar_id ]['name'],
377 'description' => $GLOBALS['wp_registered_sidebars'][ $sidebar_id ]['description'],
378 'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ) ),
379 'panel' => 'widgets',
380 'sidebar_id' => $sidebar_id,
384 * Filter Customizer widget section arguments for a given sidebar.
388 * @param array $section_args Array of Customizer widget section arguments.
389 * @param string $section_id Customizer section ID.
390 * @param int|string $sidebar_id Sidebar ID.
392 $section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
394 $section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
395 $this->manager->add_section( $section );
397 $control = new WP_Widget_Area_Customize_Control( $this->manager, $setting_id, array(
398 'section' => $section_id,
399 'sidebar_id' => $sidebar_id,
400 'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
402 $new_setting_ids[] = $setting_id;
404 $this->manager->add_control( $control );
408 // Add a control for each active widget (located in a sidebar).
409 foreach ( $sidebar_widget_ids as $i => $widget_id ) {
411 // Skip widgets that may have gone away due to a plugin being deactivated.
412 if ( ! $is_active_sidebar || ! isset( $GLOBALS['wp_registered_widgets'][$widget_id] ) ) {
416 $registered_widget = $GLOBALS['wp_registered_widgets'][$widget_id];
417 $setting_id = $this->get_setting_id( $widget_id );
418 $id_base = $GLOBALS['wp_registered_widget_controls'][$widget_id]['id_base'];
420 $control = new WP_Widget_Form_Customize_Control( $this->manager, $setting_id, array(
421 'label' => $registered_widget['name'],
422 'section' => $section_id,
423 'sidebar_id' => $sidebar_id,
424 'widget_id' => $widget_id,
425 'widget_id_base' => $id_base,
427 'width' => $wp_registered_widget_controls[$widget_id]['width'],
428 'height' => $wp_registered_widget_controls[$widget_id]['height'],
429 'is_wide' => $this->is_wide_widget( $widget_id ),
431 $this->manager->add_control( $control );
435 if ( ! $this->manager->doing_ajax( 'customize_save' ) ) {
436 foreach ( $new_setting_ids as $new_setting_id ) {
437 $this->manager->get_setting( $new_setting_id )->preview();
441 add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
445 * Covert a widget_id into its corresponding Customizer setting ID (option name).
450 * @param string $widget_id Widget ID.
451 * @return string Maybe-parsed widget ID.
453 public function get_setting_id( $widget_id ) {
454 $parsed_widget_id = $this->parse_widget_id( $widget_id );
455 $setting_id = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
457 if ( ! is_null( $parsed_widget_id['number'] ) ) {
458 $setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
464 * Determine whether the widget is considered "wide".
466 * Core widgets which may have controls wider than 250, but can
467 * still be shown in the narrow Customizer panel. The RSS and Text
468 * widgets in Core, for example, have widths of 400 and yet they
469 * still render fine in the Customizer panel. This method will
470 * return all Core widgets as being not wide, but this can be
471 * overridden with the is_wide_widget_in_customizer filter.
476 * @param string $widget_id Widget ID.
477 * @return bool Whether or not the widget is a "wide" widget.
479 public function is_wide_widget( $widget_id ) {
480 global $wp_registered_widget_controls;
482 $parsed_widget_id = $this->parse_widget_id( $widget_id );
483 $width = $wp_registered_widget_controls[$widget_id]['width'];
484 $is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases );
485 $is_wide = ( $width > 250 && ! $is_core );
488 * Filter whether the given widget is considered "wide".
492 * @param bool $is_wide Whether the widget is wide, Default false.
493 * @param string $widget_id Widget ID.
495 return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
499 * Covert a widget ID into its id_base and number components.
504 * @param string $widget_id Widget ID.
505 * @return array Array containing a widget's id_base and number components.
507 public function parse_widget_id( $widget_id ) {
513 if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
514 $parsed['id_base'] = $matches[1];
515 $parsed['number'] = intval( $matches[2] );
517 // likely an old single widget
518 $parsed['id_base'] = $widget_id;
524 * Convert a widget setting ID (option path) to its id_base and number components.
529 * @param string $setting_id Widget setting ID.
530 * @return WP_Error|array Array containing a widget's id_base and number components,
531 * or a WP_Error object.
533 public function parse_widget_setting_id( $setting_id ) {
534 if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
535 return new WP_Error( 'widget_setting_invalid_id' );
538 $id_base = $matches[2];
539 $number = isset( $matches[3] ) ? intval( $matches[3] ) : null;
541 return compact( 'id_base', 'number' );
545 * Call admin_print_styles-widgets.php and admin_print_styles hooks to
546 * allow custom styles from plugins.
551 public function print_styles() {
552 /** This action is documented in wp-admin/admin-header.php */
553 do_action( 'admin_print_styles-widgets.php' );
555 /** This action is documented in wp-admin/admin-header.php */
556 do_action( 'admin_print_styles' );
560 * Call admin_print_scripts-widgets.php and admin_print_scripts hooks to
561 * allow custom scripts from plugins.
566 public function print_scripts() {
567 /** This action is documented in wp-admin/admin-header.php */
568 do_action( 'admin_print_scripts-widgets.php' );
570 /** This action is documented in wp-admin/admin-header.php */
571 do_action( 'admin_print_scripts' );
575 * Enqueue scripts and styles for Customizer panel and export data to JavaScript.
580 public function enqueue_scripts() {
581 wp_enqueue_style( 'customize-widgets' );
582 wp_enqueue_script( 'customize-widgets' );
584 /** This action is documented in wp-admin/admin-header.php */
585 do_action( 'admin_enqueue_scripts', 'widgets.php' );
588 * Export available widgets with control_tpl removed from model
589 * since plugins need templates to be in the DOM.
591 $available_widgets = array();
593 foreach ( $this->get_available_widgets() as $available_widget ) {
594 unset( $available_widget['control_tpl'] );
595 $available_widgets[] = $available_widget;
598 $widget_reorder_nav_tpl = sprintf(
599 '<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>',
600 __( 'Move to another area…' ),
605 $move_widget_area_tpl = str_replace(
606 array( '{description}', '{btn}' ),
608 __( 'Select an area to move this widget into:' ),
609 _x( 'Move', 'Move widget' ),
611 '<div class="move-widget-area">
612 <p class="description">{description}</p>
613 <ul class="widget-area-select">
614 <% _.each( sidebars, function ( sidebar ){ %>
615 <li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
618 <div class="move-widget-actions">
619 <button class="move-widget-btn button-secondary" type="button">{btn}</button>
627 'nonce' => wp_create_nonce( 'update-widget' ),
628 'registeredSidebars' => array_values( $GLOBALS['wp_registered_sidebars'] ),
629 'registeredWidgets' => $GLOBALS['wp_registered_widgets'],
630 'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets
632 'saveBtnLabel' => __( 'Apply' ),
633 'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
634 'removeBtnLabel' => __( 'Remove' ),
635 'removeBtnTooltip' => __( 'Trash widget by moving it to the inactive widgets sidebar.' ),
636 'error' => __( 'An error has occurred. Please reload the page and try again.' ),
637 'widgetMovedUp' => __( 'Widget moved up' ),
638 'widgetMovedDown' => __( 'Widget moved down' ),
641 'widgetReorderNav' => $widget_reorder_nav_tpl,
642 'moveWidgetArea' => $move_widget_area_tpl,
646 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
647 unset( $registered_widget['callback'] ); // may not be JSON-serializeable
650 $wp_scripts->add_data(
653 sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
658 * Render the widget form control templates into the DOM.
663 public function output_widget_control_templates() {
665 <div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
666 <div id="available-widgets">
667 <div id="available-widgets-filter">
668 <label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
669 <input type="search" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets…' ) ?>" />
671 <div id="available-widgets-list">
672 <?php foreach ( $this->get_available_widgets() as $available_widget ): ?>
673 <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">
674 <?php echo $available_widget['control_tpl']; ?>
677 </div><!-- #available-widgets-list -->
678 </div><!-- #available-widgets -->
679 </div><!-- #widgets-left -->
684 * Call admin_print_footer_scripts and admin_print_scripts hooks to
685 * allow custom scripts from plugins.
690 public function print_footer_scripts() {
691 /** This action is documented in wp-admin/admin-footer.php */
692 do_action( 'admin_print_footer_scripts' );
694 /** This action is documented in wp-admin/admin-footer.php */
695 do_action( 'admin_footer-widgets.php' );
699 * Get common arguments to supply when constructing a Customizer setting.
704 * @param string $id Widget setting ID.
705 * @param array $overrides Array of setting overrides.
706 * @return array Possibly modified setting arguments.
708 public function get_setting_args( $id, $overrides = array() ) {
711 'capability' => 'edit_theme_options',
712 'transport' => 'refresh',
713 'default' => array(),
716 if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
717 $args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
718 $args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
719 } else if ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
720 $args['sanitize_callback'] = array( $this, 'sanitize_widget_instance' );
721 $args['sanitize_js_callback'] = array( $this, 'sanitize_widget_js_instance' );
724 $args = array_merge( $args, $overrides );
727 * Filter the common arguments supplied when constructing a Customizer setting.
731 * @see WP_Customize_Setting
733 * @param array $args Array of Customizer setting arguments.
734 * @param string $id Widget setting ID.
736 return apply_filters( 'widget_customizer_setting_args', $args, $id );
740 * Make sure that sidebar widget arrays only ever contain widget IDS.
742 * Used as the 'sanitize_callback' for each $sidebars_widgets setting.
747 * @param array $widget_ids Array of widget IDs.
748 * @return array Array of sanitized widget IDs.
750 public function sanitize_sidebar_widgets( $widget_ids ) {
751 $widget_ids = array_map( 'strval', (array) $widget_ids );
752 $sanitized_widget_ids = array();
753 foreach ( $widget_ids as $widget_id ) {
754 $sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
756 return $sanitized_widget_ids;
760 * Build up an index of all available widgets for use in Backbone models.
765 * @see wp_list_widgets()
767 * @return array List of available widgets.
769 public function get_available_widgets() {
770 static $available_widgets = array();
771 if ( ! empty( $available_widgets ) ) {
772 return $available_widgets;
775 global $wp_registered_widgets, $wp_registered_widget_controls;
776 require_once ABSPATH . '/wp-admin/includes/widgets.php'; // for next_widget_id_number()
778 $sort = $wp_registered_widgets;
779 usort( $sort, array( $this, '_sort_name_callback' ) );
782 foreach ( $sort as $widget ) {
783 if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget
787 $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
788 $done[] = $widget['callback'];
790 if ( ! isset( $widget['params'][0] ) ) {
791 $widget['params'][0] = array();
794 $available_widget = $widget;
795 unset( $available_widget['callback'] ); // not serializable to JSON
798 'widget_id' => $widget['id'],
799 'widget_name' => $widget['name'],
800 '_display' => 'template',
803 $is_disabled = false;
804 $is_multi_widget = ( isset( $wp_registered_widget_controls[$widget['id']]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
805 if ( $is_multi_widget ) {
806 $id_base = $wp_registered_widget_controls[$widget['id']]['id_base'];
807 $args['_temp_id'] = "$id_base-__i__";
808 $args['_multi_num'] = next_widget_id_number( $id_base );
809 $args['_add'] = 'multi';
811 $args['_add'] = 'single';
813 if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
816 $id_base = $widget['id'];
819 $list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar( array( 0 => $args, 1 => $widget['params'][0] ) );
820 $control_tpl = $this->get_widget_control( $list_widget_controls_args );
822 // The properties here are mapped to the Backbone Widget model.
823 $available_widget = array_merge( $available_widget, array(
824 'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
825 'is_multi' => $is_multi_widget,
826 'control_tpl' => $control_tpl,
827 'multi_number' => ( $args['_add'] === 'multi' ) ? $args['_multi_num'] : false,
828 'is_disabled' => $is_disabled,
829 'id_base' => $id_base,
830 'transport' => 'refresh',
831 'width' => $wp_registered_widget_controls[$widget['id']]['width'],
832 'height' => $wp_registered_widget_controls[$widget['id']]['height'],
833 'is_wide' => $this->is_wide_widget( $widget['id'] ),
836 $available_widgets[] = $available_widget;
839 return $available_widgets;
843 * Naturally order available widgets by name.
849 * @param array $widget_a The first widget to compare.
850 * @param array $widget_b The second widget to compare.
851 * @return int Reorder position for the current widget comparison.
853 protected function _sort_name_callback( $widget_a, $widget_b ) {
854 return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
858 * Get the widget control markup.
863 * @param array $args Widget control arguments.
864 * @return string Widget control form HTML markup.
866 public function get_widget_control( $args ) {
869 call_user_func_array( 'wp_widget_control', $args );
870 $replacements = array(
871 '<form method="post">' => '<div class="form">',
872 '</form>' => '</div><!-- .form -->',
875 $control_tpl = ob_get_clean();
877 $control_tpl = str_replace( array_keys( $replacements ), array_values( $replacements ), $control_tpl );
883 * Add hooks for the Customizer preview.
888 public function customize_preview_init() {
889 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
890 add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
891 add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
895 * Refresh nonce for widget updates.
900 * @param array $nonces Array of nonces.
901 * @return array $nonces Array of nonces.
903 public function refresh_nonces( $nonces ) {
904 $nonces['update-widget'] = wp_create_nonce( 'update-widget' );
909 * When previewing, make sure the proper previewing widgets are used.
911 * Because wp_get_sidebars_widgets() gets called early at init
912 * (via wp_convert_widget_settings()) and can set global variable
913 * $_wp_sidebars_widgets to the value of get_option( 'sidebars_widgets' )
914 * before the Customizer preview filter is added, we have to reset
915 * it after the filter has been added.
920 * @param array $sidebars_widgets List of widgets for the current sidebar.
922 public function preview_sidebars_widgets( $sidebars_widgets ) {
923 $sidebars_widgets = get_option( 'sidebars_widgets' );
925 unset( $sidebars_widgets['array_version'] );
926 return $sidebars_widgets;
930 * Enqueue scripts for the Customizer preview.
935 public function customize_preview_enqueue() {
936 wp_enqueue_script( 'customize-preview-widgets' );
940 * Insert default style for highlighted widget at early point so theme
941 * stylesheet can override.
946 * @action wp_print_styles
948 public function print_preview_css() {
951 .widget-customizer-highlighted-widget {
953 -webkit-box-shadow: 0 0 2px rgba(30,140,190,0.8);
954 box-shadow: 0 0 2px rgba(30,140,190,0.8);
963 * At the very end of the page, at the very end of the wp_footer,
964 * communicate the sidebars that appeared on the page.
969 public function export_preview_data() {
971 // Prepare Customizer settings to pass to JavaScript.
973 'renderedSidebars' => array_fill_keys( array_unique( $this->rendered_sidebars ), true ),
974 'renderedWidgets' => array_fill_keys( array_keys( $this->rendered_widgets ), true ),
975 'registeredSidebars' => array_values( $GLOBALS['wp_registered_sidebars'] ),
976 'registeredWidgets' => $GLOBALS['wp_registered_widgets'],
978 'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
981 foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
982 unset( $registered_widget['callback'] ); // may not be JSON-serializeable
986 <script type="text/javascript">
987 var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
993 * Keep track of the widgets that were rendered.
998 * @param array $widget Rendered widget to tally.
1000 public function tally_rendered_widgets( $widget ) {
1001 $this->rendered_widgets[ $widget['id'] ] = true;
1005 * Determine if a widget is rendered on the page.
1010 * @param string $widget_id Widget ID to check.
1011 * @return bool Whether the widget is rendered.
1013 public function is_widget_rendered( $widget_id ) {
1014 return in_array( $widget_id, $this->rendered_widgets );
1018 * Determine if a sidebar is rendered on the page.
1023 * @param string $sidebar_id Sidebar ID to check.
1024 * @return bool Whether the sidebar is rendered.
1026 public function is_sidebar_rendered( $sidebar_id ) {
1027 return in_array( $sidebar_id, $this->rendered_sidebars );
1031 * Tally the sidebars rendered via is_active_sidebar().
1033 * Keep track of the times that is_active_sidebar() is called
1034 * in the template, and assume that this means that the sidebar
1035 * would be rendered on the template if there were widgets
1041 * @param bool $is_active Whether the sidebar is active.
1042 * @param string $sidebar_id Sidebar ID.
1044 public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
1045 if ( isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] ) ) {
1046 $this->rendered_sidebars[] = $sidebar_id;
1049 * We may need to force this to true, and also force-true the value
1050 * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
1051 * is an area to drop widgets into, if the sidebar is empty.
1057 * Tally the sidebars rendered via dynamic_sidebar().
1059 * Keep track of the times that dynamic_sidebar() is called in the template,
1060 * and assume this means the sidebar would be rendered on the template if
1061 * there were widgets populating it.
1066 * @param bool $has_widgets Whether the current sidebar has widgets.
1067 * @param string $sidebar_id Sidebar ID.
1069 public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
1070 if ( isset( $GLOBALS['wp_registered_sidebars'][$sidebar_id] ) ) {
1071 $this->rendered_sidebars[] = $sidebar_id;
1075 * We may need to force this to true, and also force-true the value
1076 * for 'is_active_sidebar' if we want to ensure there is an area to
1077 * drop widgets into, if the sidebar is empty.
1079 return $has_widgets;
1083 * Get MAC for a serialized widget instance string.
1085 * Allows values posted back from JS to be rejected if any tampering of the
1086 * data has occurred.
1091 * @param string $serialized_instance Widget instance.
1092 * @return string MAC for serialized widget instance.
1094 protected function get_instance_hash_key( $serialized_instance ) {
1095 return wp_hash( $serialized_instance );
1099 * Sanitize a widget instance.
1101 * Unserialize the JS-instance for storing in the options. It's important
1102 * that this filter only get applied to an instance once.
1107 * @param array $value Widget instance to sanitize.
1108 * @return array Sanitized widget instance.
1110 public function sanitize_widget_instance( $value ) {
1111 if ( $value === array() ) {
1115 if ( empty( $value['is_widget_customizer_js_value'] )
1116 || empty( $value['instance_hash_key'] )
1117 || empty( $value['encoded_serialized_instance'] ) )
1122 $decoded = base64_decode( $value['encoded_serialized_instance'], true );
1123 if ( false === $decoded ) {
1127 if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
1131 $instance = unserialize( $decoded );
1132 if ( false === $instance ) {
1140 * Convert widget instance into JSON-representable format.
1145 * @param array $value Widget instance to convert to JSON.
1146 * @return array JSON-converted widget instance.
1148 public function sanitize_widget_js_instance( $value ) {
1149 if ( empty( $value['is_widget_customizer_js_value'] ) ) {
1150 $serialized = serialize( $value );
1153 'encoded_serialized_instance' => base64_encode( $serialized ),
1154 'title' => empty( $value['title'] ) ? '' : $value['title'],
1155 'is_widget_customizer_js_value' => true,
1156 'instance_hash_key' => $this->get_instance_hash_key( $serialized ),
1163 * Strip out widget IDs for widgets which are no longer registered.
1165 * One example where this might happen is when a plugin orphans a widget
1166 * in a sidebar upon deactivation.
1171 * @param array $widget_ids List of widget IDs.
1172 * @return array Parsed list of widget IDs.
1174 public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
1175 global $wp_registered_widgets;
1176 $widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
1181 * Find and invoke the widget update and control callbacks.
1183 * Requires that $_POST be populated with the instance data.
1188 * @param string $widget_id Widget ID.
1189 * @return WP_Error|array Array containing the updated widget information.
1190 * A WP_Error object, otherwise.
1192 public function call_widget_update( $widget_id ) {
1193 global $wp_registered_widget_updates, $wp_registered_widget_controls;
1195 $this->start_capturing_option_updates();
1196 $parsed_id = $this->parse_widget_id( $widget_id );
1197 $option_name = 'widget_' . $parsed_id['id_base'];
1200 * If a previously-sanitized instance is provided, populate the input vars
1201 * with its values so that the widget update callback will read this instance
1203 $added_input_vars = array();
1204 if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
1205 $sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
1206 if ( false === $sanitized_widget_setting ) {
1207 $this->stop_capturing_option_updates();
1208 return new WP_Error( 'widget_setting_malformed' );
1211 $instance = $this->sanitize_widget_instance( $sanitized_widget_setting );
1212 if ( is_null( $instance ) ) {
1213 $this->stop_capturing_option_updates();
1214 return new WP_Error( 'widget_setting_unsanitized' );
1217 if ( ! is_null( $parsed_id['number'] ) ) {
1219 $value[$parsed_id['number']] = $instance;
1220 $key = 'widget-' . $parsed_id['id_base'];
1221 $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1222 $added_input_vars[] = $key;
1224 foreach ( $instance as $key => $value ) {
1225 $_REQUEST[$key] = $_POST[$key] = wp_slash( $value );
1226 $added_input_vars[] = $key;
1231 // Invoke the widget update callback.
1232 foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
1233 if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
1235 call_user_func_array( $control['callback'], $control['params'] );
1241 // Clean up any input vars that were manually added
1242 foreach ( $added_input_vars as $key ) {
1243 unset( $_POST[ $key ] );
1244 unset( $_REQUEST[ $key ] );
1247 // Make sure the expected option was updated.
1248 if ( 0 !== $this->count_captured_options() ) {
1249 if ( $this->count_captured_options() > 1 ) {
1250 $this->stop_capturing_option_updates();
1251 return new WP_Error( 'widget_setting_too_many_options' );
1254 $updated_option_name = key( $this->get_captured_options() );
1255 if ( $updated_option_name !== $option_name ) {
1256 $this->stop_capturing_option_updates();
1257 return new WP_Error( 'widget_setting_unexpected_option' );
1261 // Obtain the widget instance.
1262 $option = $this->get_captured_option( $option_name );
1263 if ( null !== $parsed_id['number'] ) {
1264 $instance = $option[ $parsed_id['number'] ];
1266 $instance = $option;
1270 * Override the incoming $_POST['customized'] for a newly-created widget's
1271 * setting with the new $instance so that the preview filter currently
1272 * in place from WP_Customize_Setting::preview() will use this value
1273 * instead of the default widget instance value (an empty array).
1275 $setting_id = $this->get_setting_id( $widget_id );
1276 $this->manager->set_post_value( $setting_id, $instance );
1278 // Obtain the widget control with the updated instance in place.
1280 $form = $wp_registered_widget_controls[ $widget_id ];
1282 call_user_func_array( $form['callback'], $form['params'] );
1284 $form = ob_get_clean();
1286 $this->stop_capturing_option_updates();
1288 return compact( 'instance', 'form' );
1292 * Update widget settings asynchronously.
1294 * Allows the Customizer to update a widget using its form, but return the new
1295 * instance info via Ajax instead of saving it to the options table.
1297 * Most code here copied from wp_ajax_save_widget()
1302 * @see wp_ajax_save_widget()
1305 public function wp_ajax_update_widget() {
1307 if ( ! is_user_logged_in() ) {
1311 check_ajax_referer( 'update-widget', 'nonce' );
1313 if ( ! current_user_can( 'edit_theme_options' ) ) {
1317 if ( empty( $_POST['widget-id'] ) ) {
1318 wp_send_json_error( 'missing_widget-id' );
1321 /** This action is documented in wp-admin/includes/ajax-actions.php */
1322 do_action( 'load-widgets.php' );
1324 /** This action is documented in wp-admin/includes/ajax-actions.php */
1325 do_action( 'widgets.php' );
1327 /** This action is documented in wp-admin/widgets.php */
1328 do_action( 'sidebar_admin_setup' );
1330 $widget_id = $this->get_post_value( 'widget-id' );
1331 $parsed_id = $this->parse_widget_id( $widget_id );
1332 $id_base = $parsed_id['id_base'];
1334 $is_updating_widget_template = (
1335 isset( $_POST[ 'widget-' . $id_base ] )
1337 is_array( $_POST[ 'widget-' . $id_base ] )
1339 preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
1341 if ( $is_updating_widget_template ) {
1342 wp_send_json_error( 'template_widget_not_updatable' );
1345 $updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
1346 if ( is_wp_error( $updated_widget ) ) {
1347 wp_send_json_error( $updated_widget->get_error_message() );
1350 $form = $updated_widget['form'];
1351 $instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );
1353 wp_send_json_success( compact( 'form', 'instance' ) );
1356 /***************************************************************************
1357 * Option Update Capturing
1358 ***************************************************************************/
1361 * List of captured widget option updates.
1365 * @var array $_captured_options Values updated while option capture is happening.
1367 protected $_captured_options = array();
1370 * Whether option capture is currently happening.
1374 * @var bool $_is_current Whether option capture is currently happening or not.
1376 protected $_is_capturing_option_updates = false;
1379 * Determine whether the captured option update should be ignored.
1384 * @param string $option_name Option name.
1385 * @return boolean Whether the option capture is ignored.
1387 protected function is_option_capture_ignored( $option_name ) {
1388 return ( 0 === strpos( $option_name, '_transient_' ) );
1392 * Retrieve captured widget option updates.
1397 * @return array Array of captured options.
1399 protected function get_captured_options() {
1400 return $this->_captured_options;
1404 * Get the option that was captured from being saved.
1409 * @param string $option_name Option name.
1410 * @param mixed $default Optional. Default value to return if the option does not exist.
1411 * @return mixed Value set for the option.
1413 protected function get_captured_option( $option_name, $default = false ) {
1414 if ( array_key_exists( $option_name, $this->_captured_options ) ) {
1415 $value = $this->_captured_options[ $option_name ];
1423 * Get the number of captured widget option updates.
1428 * @return int Number of updated options.
1430 protected function count_captured_options() {
1431 return count( $this->_captured_options );
1435 * Start keeping track of changes to widget options, caching new values.
1440 protected function start_capturing_option_updates() {
1441 if ( $this->_is_capturing_option_updates ) {
1445 $this->_is_capturing_option_updates = true;
1447 add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
1451 * Pre-filter captured option values before updating.
1456 * @param mixed $new_value The new option value.
1457 * @param string $option_name Name of the option.
1458 * @param mixed $old_value The old option value.
1459 * @return mixed Filtered option value.
1461 public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
1462 if ( $this->is_option_capture_ignored( $option_name ) ) {
1466 if ( ! isset( $this->_captured_options[ $option_name ] ) ) {
1467 add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1470 $this->_captured_options[ $option_name ] = $new_value;
1476 * Pre-filter captured option values before retrieving.
1481 * @param mixed $value Value to return instead of the option value.
1482 * @return mixed Filtered option value.
1484 public function capture_filter_pre_get_option( $value ) {
1485 $option_name = preg_replace( '/^pre_option_/', '', current_filter() );
1487 if ( isset( $this->_captured_options[ $option_name ] ) ) {
1488 $value = $this->_captured_options[ $option_name ];
1490 /** This filter is documented in wp-includes/option.php */
1491 $value = apply_filters( 'option_' . $option_name, $value );
1498 * Undo any changes to the options since options capture began.
1503 protected function stop_capturing_option_updates() {
1504 if ( ! $this->_is_capturing_option_updates ) {
1508 remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
1510 foreach ( array_keys( $this->_captured_options ) as $option_name ) {
1511 remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
1514 $this->_captured_options = array();
1515 $this->_is_capturing_option_updates = false;
1520 * @deprecated 4.2.0 Deprecated in favor of customize_dynamic_setting_args filter.
1522 public function setup_widget_addition_previews() {
1523 _deprecated_function( __METHOD__, '4.2.0' );
1528 * @deprecated 4.2.0 Deprecated in favor of customize_dynamic_setting_args filter.
1530 public function prepreview_added_sidebars_widgets() {
1531 _deprecated_function( __METHOD__, '4.2.0' );
1536 * @deprecated 4.2.0 Deprecated in favor of customize_dynamic_setting_args filter.
1538 public function prepreview_added_widget_instance() {
1539 _deprecated_function( __METHOD__, '4.2.0' );
1544 * @deprecated 4.2.0 Deprecated in favor of customize_dynamic_setting_args filter.
1546 public function remove_prepreview_filters() {
1547 _deprecated_function( __METHOD__, '4.2.0' );