WC_REST_Paypal_Standard_Controller::rebuild_cart_from_order │ private │ WC 1.0

Rebuild the session cart.

Метод класса: WC_REST_Paypal_Standard_Controller{}

Хуков нет.

Возвращает

null. Ничего (null).

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

// private - только в коде основоного (родительского) класса
$result = $this->rebuild_cart_from_order( $order ): void;
$order(WC_Order) (обязательный)
The order object.

Код WC_REST_Paypal_Standard_Controller::rebuild_cart_from_order() WC 11.3.0

private function rebuild_cart_from_order( $order ): void {
	wc_load_cart();
	WC()->cart->empty_cart();
	foreach ( $order->get_items() as $item ) {
		if ( ! ( $item instanceof WC_Order_Item_Product ) ) {
			continue;
		}

		$product_id = $item->get_product_id();
		$product    = $item->get_product();

		if ( ! $product instanceof WC_Product ) {
			continue;
		}

		$order_product_subtotal = (float) $item->get_subtotal();
		$order_product_quantity = (float) $item->get_quantity();
		$order_product_price    = round( $order_product_subtotal / $order_product_quantity, wc_get_price_decimals() );

		if ( $product->is_type( ProductType::VARIATION ) ) {
			$variation_id  = $item->get_variation_id();
			$cart_item_key = WC()->cart->add_to_cart(
				$product_id,
				$item->get_quantity(),
				$variation_id,
				$this->get_variation_attributes_from_order_item( $item, $product_id )
			);
		} else {
			$cart_item_key = WC()->cart->add_to_cart( $product_id, $item->get_quantity() );
		}

		if ( ! is_string( $cart_item_key ) ) {
			throw new Exception( 'Failed to add product to cart.' );
		}

		$cart_item = WC()->cart->get_cart_item( $cart_item_key );
		if ( ! $cart_item ) {
			throw new Exception( 'Failed to get cart item.' );
		}

		$cart_item['data']->set_price( (string) $order_product_price );
	}

	// Re-apply coupons present on the order so discounts/totals are accurate.
	if ( method_exists( $order, 'get_coupon_codes' ) ) {
		foreach ( (array) $order->get_coupon_codes() as $code ) {
			if ( $code ) {
				WC()->cart->apply_coupon( $code );
			}
		}
	}

	// Recalculate the cart totals after all changes have been applied.
	// Note that fees are handled via a hook.
	WC()->cart->calculate_totals();

	// Re-apply shipping methods present on the order so totals are accurate.
	$order_shipping_rate_id = $this->get_order_shipping_rate_id( $order );
	if ( ! empty( $order_shipping_rate_id ) ) {
		WC()->session->set( 'chosen_shipping_methods', array( $order_shipping_rate_id ) );
	}
}