WP_REST_Templates_Controller::update_item()publicWP 5.8.0

Updates a single template.

{} It's a method of the class: WP_REST_Templates_Controller{}

Hooks from the method

Return

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

Usage

$WP_REST_Templates_Controller = new WP_REST_Templates_Controller();
$WP_REST_Templates_Controller->update_item( $request );
$request(WP_REST_Request) (required)
Full details about the request.

Changelog

Since 5.8.0 Introduced.

Code of WP_REST_Templates_Controller::update_item() WP 6.0

public function update_item( $request ) {
	$template = get_block_template( $request['id'], $this->post_type );
	if ( ! $template ) {
		return new WP_Error( 'rest_template_not_found', __( 'No templates exist with that id.' ), array( 'status' => 404 ) );
	}

	$post_before = get_post( $template->wp_id );

	if ( isset( $request['source'] ) && 'theme' === $request['source'] ) {
		wp_delete_post( $template->wp_id, true );
		$request->set_param( 'context', 'edit' );

		$template = get_block_template( $request['id'], $this->post_type );
		$response = $this->prepare_item_for_response( $template, $request );

		return rest_ensure_response( $response );
	}

	$changes = $this->prepare_item_for_database( $request );

	if ( is_wp_error( $changes ) ) {
		return $changes;
	}

	if ( 'custom' === $template->source ) {
		$update = true;
		$result = wp_update_post( wp_slash( (array) $changes ), false );
	} else {
		$update      = false;
		$post_before = null;
		$result      = wp_insert_post( wp_slash( (array) $changes ), false );
	}

	if ( is_wp_error( $result ) ) {
		if ( 'db_update_error' === $result->get_error_code() ) {
			$result->add_data( array( 'status' => 500 ) );
		} else {
			$result->add_data( array( 'status' => 400 ) );
		}
		return $result;
	}

	$template      = get_block_template( $request['id'], $this->post_type );
	$fields_update = $this->update_additional_fields_for_object( $template, $request );
	if ( is_wp_error( $fields_update ) ) {
		return $fields_update;
	}

	$request->set_param( 'context', 'edit' );

	$post = get_post( $template->wp_id );
	/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */
	do_action( "rest_after_insert_{$this->post_type}", $post, $request, false );

	wp_after_insert_post( $post, $update, $post_before );

	$response = $this->prepare_item_for_response( $template, $request );

	return rest_ensure_response( $response );
}