W3cubDocs

/WordPress

WP_Customize_Widgets::wp_ajax_update_widget()

Updates widget settings asynchronously.

Description

Allows the Customizer to update a widget using its form, but return the new instance info via Ajax instead of saving it to the options table.

Most code here copied from wp_ajax_save_widget().

See also

Source

File: wp-includes/class-wp-customize-widgets.php

public function wp_ajax_update_widget() {

		if ( ! is_user_logged_in() ) {
			wp_die( 0 );
		}

		check_ajax_referer( 'update-widget', 'nonce' );

		if ( ! current_user_can( 'edit_theme_options' ) ) {
			wp_die( -1 );
		}

		if ( empty( $_POST['widget-id'] ) ) {
			wp_send_json_error( 'missing_widget-id' );
		}

		/** This action is documented in wp-admin/includes/ajax-actions.php */
		do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

		/** This action is documented in wp-admin/includes/ajax-actions.php */
		do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

		/** This action is documented in wp-admin/widgets.php */
		do_action( 'sidebar_admin_setup' );

		$widget_id = $this->get_post_value( 'widget-id' );
		$parsed_id = $this->parse_widget_id( $widget_id );
		$id_base   = $parsed_id['id_base'];

		$is_updating_widget_template = (
			isset( $_POST[ 'widget-' . $id_base ] )
			&&
			is_array( $_POST[ 'widget-' . $id_base ] )
			&&
			preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
		);
		if ( $is_updating_widget_template ) {
			wp_send_json_error( 'template_widget_not_updatable' );
		}

		$updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
		if ( is_wp_error( $updated_widget ) ) {
			wp_send_json_error( $updated_widget->get_error_code() );
		}

		$form     = $updated_widget['form'];
		$instance = $this->sanitize_widget_js_instance( $updated_widget['instance'] );

		wp_send_json_success( compact( 'form', 'instance' ) );
	}

Changelog

Version Description
3.9.0 Introduced.

© 2003–2019 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/classes/wp_customize_widgets/wp_ajax_update_widget