Automattic\WooCommerce\Internal\Orders

OrderActionsRestController::maybe_update_billing_emailprivateWC 1.0

Update the billing email of an order when certain conditions are met.

If the order does not already have a billing email, it will be updated. If it does have one, but $force is set to true, it will be updated. Otherwise this will return an error. This can also return an error if the given email address is not valid.

Method of the class: OrderActionsRestController{}

No Hooks.

Returns

String|WP_Error. A message upon success, otherwise an error.

Usage

// private - for code of main (parent) class only
$result = $this->maybe_update_billing_email( $order, $email, ?bool $force );
$order(WC_Order) (required)
The order to update.
$email(string) (required)
The email address to maybe add to the order.
?bool $force
.
Default: false

OrderActionsRestController::maybe_update_billing_email() code WC 9.8.5

private function maybe_update_billing_email( WC_Order $order, string $email, ?bool $force = false ) {
	$existing_email = $order->get_billing_email( 'edit' );

	if ( $existing_email === $email ) {
		return '';
	}

	if ( $existing_email && true !== $force ) {
		return new WP_Error(
			'woocommerce_rest_order_billing_email_exists',
			__( 'Order already has a billing email.', 'woocommerce' ),
			array( 'status' => 400 )
		);
	}

	try {
		$order->set_billing_email( $email );
		$order->save();
	} catch ( WC_Data_Exception $e ) {
		return new WP_Error(
			$e->getErrorCode(),
			$e->getMessage()
		);
	}

	return sprintf(
		// translators: %s is an email address.
		__( 'Billing email updated to %s.', 'woocommerce' ),
		esc_html( $email )
	);
}