WP_REST_Widgets_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error

In this article

Updates an existing widget.

Parameters

$requestWP_REST_Requestrequired
Full details about the request.

Return

WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.

Source

public function update_item( $request ) {
	global $wp_widget_factory;

	/*
	 * retrieve_widgets() contains logic to move "hidden" or "lost" widgets to the
	 * wp_inactive_widgets sidebar based on the contents of the $sidebars_widgets global.
	 *
	 * When batch requests are processed, this global is not properly updated by previous
	 * calls, resulting in widgets incorrectly being moved to the wp_inactive_widgets
	 * sidebar.
	 *
	 * See https://core.trac.wordpress.org/ticket/53657.
	 */
	wp_get_sidebars_widgets();
	$this->retrieve_widgets();

	$widget_id  = $request['id'];
	$sidebar_id = wp_find_widgets_sidebar( $widget_id );

	// Allow sidebar to be unset or missing when widget is not a WP_Widget.
	$parsed_id     = wp_parse_widget_id( $widget_id );
	$widget_object = $wp_widget_factory->get_widget_object( $parsed_id['id_base'] );
	if ( is_null( $sidebar_id ) && $widget_object ) {
		return new WP_Error(
			'rest_widget_not_found',
			__( 'No widget was found with that id.' ),
			array( 'status' => 404 )
		);
	}

	if (
		$request->has_param( 'instance' ) ||
		$request->has_param( 'form_data' )
	) {
		$maybe_error = $this->save_widget( $request, $sidebar_id );
		if ( is_wp_error( $maybe_error ) ) {
			return $maybe_error;
		}
	}

	if ( $request->has_param( 'sidebar' ) ) {
		if ( $sidebar_id !== $request['sidebar'] ) {
			$sidebar_id = $request['sidebar'];
			wp_assign_widget_to_sidebar( $widget_id, $sidebar_id );
		}
	}

	$request['context'] = 'edit';

	return $this->prepare_item_for_response( compact( 'widget_id', 'sidebar_id' ), $request );
}

Changelog

VersionDescription
5.8.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.