WP_REST_Autosaves_Controller::create_item() WordPress Method

The WP_REST_Autosaves_Controller::create_item() method creates a new autosave for a post. The method accepts two arguments: the post ID and the autosave data. The method returns the newly created autosave object.

WP_REST_Autosaves_Controller::create_item( WP_REST_Request $request ) #

Creates, updates or deletes an autosave revision.


Parameters

$request

(WP_REST_Request)(Required)Full details about the request.


Top ↑

Return

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


Top ↑

Source

File: wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php

	public function create_item( $request ) {

		if ( ! defined( 'DOING_AUTOSAVE' ) ) {
			define( 'DOING_AUTOSAVE', true );
		}

		$post = get_post( $request['id'] );

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

		$prepared_post     = $this->parent_controller->prepare_item_for_database( $request );
		$prepared_post->ID = $post->ID;
		$user_id           = get_current_user_id();

		if ( ( 'draft' === $post->post_status || 'auto-draft' === $post->post_status ) && $post->post_author == $user_id ) {
			// Draft posts for the same author: autosaving updates the post and does not create a revision.
			// Convert the post object to an array and add slashes, wp_update_post() expects escaped array.
			$autosave_id = wp_update_post( wp_slash( (array) $prepared_post ), true );
		} else {
			// Non-draft posts: create or update the post autosave.
			$autosave_id = $this->create_post_autosave( (array) $prepared_post );
		}

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

		$autosave = get_post( $autosave_id );
		$request->set_param( 'context', 'edit' );

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

		return $response;
	}


Top ↑

Changelog

Changelog
VersionDescription
5.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.