WC_REST_Products_V1_Controller::create_item
Create a single product.
Method of the class: WC_REST_Products_V1_Controller{}
Hooks from the method
Returns
WP_Error|WP_REST_Response.
Usage
$WC_REST_Products_V1_Controller = new WC_REST_Products_V1_Controller(); $WC_REST_Products_V1_Controller->create_item( $request );
- $request(WP_REST_Request) (required)
- Full details about the request.
WC_REST_Products_V1_Controller::create_item() WC REST Products V1 Controller::create item code WC 10.7.0
public function create_item( $request ) {
if ( ! empty( $request['id'] ) ) {
return new WP_Error( "woocommerce_rest_{$this->post_type}_exists", sprintf( __( 'Cannot create existing %s.', 'woocommerce' ), $this->post_type ), array( 'status' => 400 ) );
}
$product_id = 0;
try {
$product_id = $this->save_product( $request );
$post = get_post( $product_id );
$this->update_additional_fields_for_object( $post, $request );
$this->update_post_meta_fields( $post, $request );
/**
* Fires after a single item is created or updated via the REST API.
*
* @param WP_Post $post Post data.
* @param WP_REST_Request $request Request object.
* @param boolean $creating True when creating item, false when updating.
*/
do_action( 'woocommerce_rest_insert_product', $post, $request, true );
$request->set_param( 'context', 'edit' );
$response = $this->prepare_item_for_response( $post, $request );
$response = rest_ensure_response( $response );
$response->set_status( 201 );
$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $post->ID ) ) );
return $response;
} catch ( WC_Data_Exception $e ) {
$this->delete_post( $product_id );
return new WP_Error( $e->getErrorCode(), $e->getMessage(), $e->getErrorData() );
} catch ( WC_REST_Exception $e ) {
$this->delete_post( $product_id );
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}