Automattic\WooCommerce\Internal\Orders

CouponsController::add_coupon_discount()publicWC 1.0

Add order discount programmatically.

{} Это метод класса: CouponsController{}

Хуков нет.

Возвращает

Объект. The retrieved order object.

Использование

$CouponsController = new CouponsController();
$CouponsController->add_coupon_discount( $post_variables ): object;
$post_variables(массив) (обязательный)
Contents of the $_POST array that would be passed in an Ajax call.

Код CouponsController::add_coupon_discount() WC 6.9.1

public function add_coupon_discount( array $post_variables ): object {
	$order_id           = isset( $post_variables['order_id'] ) ? absint( $post_variables['order_id'] ) : 0;
	$order              = wc_get_order( $order_id );
	$calculate_tax_args = array(
		'country'  => isset( $post_variables['country'] ) ? wc_strtoupper( wc_clean( wp_unslash( $post_variables['country'] ) ) ) : '',
		'state'    => isset( $post_variables['state'] ) ? wc_strtoupper( wc_clean( wp_unslash( $post_variables['state'] ) ) ) : '',
		'postcode' => isset( $post_variables['postcode'] ) ? wc_strtoupper( wc_clean( wp_unslash( $post_variables['postcode'] ) ) ) : '',
		'city'     => isset( $post_variables['city'] ) ? wc_strtoupper( wc_clean( wp_unslash( $post_variables['city'] ) ) ) : '',
	);

	if ( ! $order ) {
		throw new Exception( __( 'Invalid order', 'woocommerce' ) );
	}

	if ( empty( $post_variables['coupon'] ) ) {
		throw new Exception( __( 'Invalid coupon', 'woocommerce' ) );
	}

	// Add user ID and/or email so validation for coupon limits works.
	$user_id_arg    = isset( $post_variables['user_id'] ) ? absint( $post_variables['user_id'] ) : 0;
	$user_email_arg = isset( $post_variables['user_email'] ) ? sanitize_email( wp_unslash( $post_variables['user_email'] ) ) : '';

	if ( $user_id_arg ) {
		$order->set_customer_id( $user_id_arg );
	}
	if ( $user_email_arg ) {
		$order->set_billing_email( $user_email_arg );
	}

	$order->calculate_taxes( $calculate_tax_args );
	$order->calculate_totals( false );

	$result = $order->apply_coupon( wc_format_coupon_code( wp_unslash( $post_variables['coupon'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

	if ( is_wp_error( $result ) ) {
		throw new Exception( html_entity_decode( wp_strip_all_tags( $result->get_error_message() ) ) );
	}

	return $order;
}