Automattic\WooCommerce\Internal\RestApi\Routes\V4\Customers
Controller::create_item
Create a single customer.
Method of the class: Controller{}
Hooks from the method
Returns
WP_Error|WP_REST_Response.
Usage
$Controller = new Controller(); $Controller->create_item( $request );
- $request(WP_REST_Request) (required)
- Full details about the request.
Controller::create_item() Controller::create item code WC 11.2.2
public function create_item( $request ) {
if ( ! empty( $request['id'] ) ) {
return $this->get_route_error_by_code( self::RESOURCE_EXISTS );
}
try {
// 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_utils->update_customer_from_request( $customer, $request, true );
if ( ! $customer->get_id() ) {
return $this->get_route_error_by_code( self::CANNOT_CREATE );
}
$user_data = get_userdata( $customer->get_id() );
$this->update_additional_fields_for_object( $user_data, $request );
/**
* Fires after a customer is created via the REST API.
*
* @param WP_User $user_data Data used to create the customer.
* @param WP_REST_Request $request Request object.
* @since 10.2.0
*/
do_action( $this->get_hook_prefix() . 'created', $user_data, $request );
$request->set_param( 'context', 'edit' );
$response = $this->prepare_item_for_response( $customer, $request );
$response->set_status( WP_Http::CREATED );
$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $customer->get_id() ) ) );
return $response;
} catch ( \WC_REST_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
} catch ( \Exception $e ) {
return $this->get_route_error_by_code( self::CANNOT_CREATE );
}
}