public function create_item($request)
{
if (!empty($request['id'])) {
/* translators: %s: post type */
return new WP_Error("woocommerce_rest_{$this->post_type}_exists", sprintf(__('Cannot create existing %s.', 'woocommerce'), $this->post_type), array('status' => 400));
}
$post = $this->prepare_item_for_database($request);
if (is_wp_error($post)) {
return $post;
}
$post->post_type = $this->post_type;
$post_id = wp_insert_post($post, true);
if (is_wp_error($post_id)) {
if (in_array($post_id->get_error_code(), array('db_insert_error'))) {
$post_id->add_data(array('status' => 500));
} else {
$post_id->add_data(array('status' => 400));
}
return $post_id;
}
$post->ID = $post_id;
$post = get_post($post_id);
$this->update_additional_fields_for_object($post, $request);
// Add meta fields.
$meta_fields = $this->add_post_meta_fields($post, $request);
if (is_wp_error($meta_fields)) {
// Remove post.
$this->delete_post($post);
return $meta_fields;
}
/**
* Fires after a single item is created or updated via the REST API.
*
* @param object $post Inserted object (not a WP_Post object).
* @param WP_REST_Request $request Request object.
* @param boolean $creating True when creating item, false when updating.
*/
do_action("woocommerce_rest_insert_{$this->post_type}", $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;
}