WC_API_Customers::create_customer()publicWC 2.2

Create a customer

Method of the class: WC_API_Customers{}

Return

Array|WP_Error.

Usage

$WC_API_Customers = new WC_API_Customers();
$WC_API_Customers->create_customer( $data );
$data(array) (required)
-

Changelog

Since 2.2 Introduced.

WC_API_Customers::create_customer() code WC 8.6.1

public function create_customer( $data ) {
	try {
		if ( ! isset( $data['customer'] ) ) {
			throw new WC_API_Exception( 'woocommerce_api_missing_customer_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'customer' ), 400 );
		}

		$data = $data['customer'];

		// Checks with can create new users.
		if ( ! current_user_can( 'create_users' ) ) {
			throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_customer', __( 'You do not have permission to create this customer', 'woocommerce' ), 401 );
		}

		$data = apply_filters( 'woocommerce_api_create_customer_data', $data, $this );

		// Checks with the email is missing.
		if ( ! isset( $data['email'] ) ) {
			throw new WC_API_Exception( 'woocommerce_api_missing_customer_email', sprintf( __( 'Missing parameter %s', 'woocommerce' ), 'email' ), 400 );
		}

		// Create customer.
		$customer = new WC_Customer;
		$customer->set_username( ! empty( $data['username'] ) ? $data['username'] : '' );
		$customer->set_password( ! empty( $data['password'] ) ? $data['password'] : '' );
		$customer->set_email( $data['email'] );
		$customer->save();

		if ( ! $customer->get_id() ) {
			throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_customer', __( 'This resource cannot be created.', 'woocommerce' ), 400 );
		}

		// Added customer data.
		$this->update_customer_data( $customer->get_id(), $data, $customer );
		$customer->save();

		do_action( 'woocommerce_api_create_customer', $customer->get_id(), $data );

		$this->server->send_status( 201 );

		return $this->get_customer( $customer->get_id() );
	} catch ( Exception $e ) {
		return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
	}
}