WC_REST_Customers_V1_Controller::create_item() public WC 1.0
Create a single customer.
{} It's a method of the class: WC_REST_Customers_V1_Controller{}
Hooks from the method
Return
WP_Error|WP_REST_Response.
Usage
$WC_REST_Customers_V1_Controller = new WC_REST_Customers_V1_Controller(); $WC_REST_Customers_V1_Controller->create_item( $request );
- $request(WP_REST_Request) (required)
- Full details about the request.
Code of WC_REST_Customers_V1_Controller::create_item() WC REST Customers V1 Controller::create item WC 5.0.0
public function create_item( $request ) {
try {
if ( ! empty( $request['id'] ) ) {
throw new WC_REST_Exception( 'woocommerce_rest_customer_exists', __( 'Cannot create existing resource.', 'woocommerce' ), 400 );
}
// Sets the username.
$request['username'] = ! empty( $request['username'] ) ? $request['username'] : '';
// Sets the password.
$request['password'] = ! empty( $request['password'] ) ? $request['password'] : '';
// Create customer.
$customer = new WC_Customer;
$customer->set_username( $request['username'] );
$customer->set_password( $request['password'] );
$customer->set_email( $request['email'] );
$this->update_customer_meta_fields( $customer, $request );
$customer->save();
if ( ! $customer->get_id() ) {
throw new WC_REST_Exception( 'woocommerce_rest_cannot_create', __( 'This resource cannot be created.', 'woocommerce' ), 400 );
}
$user_data = get_userdata( $customer->get_id() );
$this->update_additional_fields_for_object( $user_data, $request );
/**
* Fires after a customer is created or updated via the REST API.
*
* @param WP_User $user_data Data used to create the customer.
* @param WP_REST_Request $request Request object.
* @param boolean $creating True when creating customer, false when updating customer.
*/
do_action( 'woocommerce_rest_insert_customer', $user_data, $request, true );
$request->set_param( 'context', 'edit' );
$response = $this->prepare_item_for_response( $user_data, $request );
$response = rest_ensure_response( $response );
$response->set_status( 201 );
$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $customer->get_id() ) ) );
return $response;
} catch ( Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}