WC_API_Customers::create_customer( array $data )

Create a customer


Description Description


Parameters Parameters

$data

(Required)


Top ↑

Return Return

(array|WP_Error)


Top ↑

Source Source

File: includes/legacy/api/v2/class-wc-api-customers.php

	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() ) );
		}
	}

Top ↑

Changelog Changelog

Changelog
Version Description
2.2 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.