Рассчитать способы доставки / ставки в рамках существующего заказа в WooCommerce - PullRequest
5 голосов
/ 13 марта 2019

Я, по сути, пытаюсь повторить функциональность, как на странице корзины, где пользователь может добавить свои zip code, и он рассчитывает доступные тарифы на доставку, но я пытаюсь сделать это из бэкэнда из уже созданного заказ.

Я не смог найти способ сделать это напрямую из экземпляра WC_Order, поэтому следующая лучшая вещь, которую я имею, - это очистить сеанс корзины, добавить все элементы из порядка в сеанс корзины, а затем попытаться вычислить его.

Вот что у меня есть. Я всегда застрял на том, как рассчитать ставки для всего заказа.

$order_id       = isset($_POST['order_id'])?$_POST['order_id']:0;
$country        = isset($_POST['country'])?$_POST['country']:0;
$state          = isset($_POST['state'])?$_POST['state']:0;
$postcode       = isset($_POST['postcode'])?$_POST['postcode']:0;
$city           = isset($_POST['city'])?$_POST['country']:0;
$order          = wc_get_order( $order_id );
$order_items    = $order->get_items();

// Don't know if this would save country of logged in user, or only create a temporary guest user session which is what I'd need
if ( $country != '' ) {
    WC()->customer->set_billing_location( $country, $state, $postcode, $city );
    WC()->customer->set_shipping_location( $country, $state, $postcode, $city );
} else {
    WC()->customer->set_billing_address_to_base();
    WC()->customer->set_shipping_address_to_base();
}

// Remove all current items from cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
    WC()->cart->empty_cart();
}

// Add all items from the order to the cart
foreach ($order_items as $order_item) {
    WC()->cart->add_to_cart($order_item['product_id'], $order_item['qty']);
}

$totals = WC()->shipping->get_packages();

// $totals returns rates but I believe it is per each "package". It's not a cumulative rate like the cart page shows.

Ответы [ 2 ]

3 голосов
/ 19 марта 2019

Ладно, благодаря @mujuonly, я смог это выяснить.

Вот как получить все рассчитанные тарифы доставки, так же, как это показано на странице корзины.

// Post variables
$order_id   = isset($_POST['order_id'])?$_POST['order_id']:0;
$country    = isset($_POST['country'])?$_POST['country']:0;
$state      = isset($_POST['state'])?$_POST['state']:0;
$postcode   = isset($_POST['postcode'])?$_POST['postcode']:0;
$city       = isset($_POST['city'])?$_POST['city']:0;

// Order and order items
$order          = wc_get_order( $order_id );
$order_items    = $order->get_items();

// Reset shipping first
WC()->shipping()->reset_shipping();

// Set correct temporary location
if ( $country != '' ) {
    WC()->customer->set_billing_location( $country, $state, $postcode, $city );
    WC()->customer->set_shipping_location( $country, $state, $postcode, $city );
} else {
    WC()->customer->set_billing_address_to_base();
    WC()->customer->set_shipping_address_to_base();
}

// Remove all current items from cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
    WC()->cart->empty_cart();
}

// Add all items to cart
foreach ($order_items as $order_item) {
    WC()->cart->add_to_cart($order_item['product_id'], $order_item['qty']);
}

// Calculate shipping
$packages = WC()->cart->get_shipping_packages();
$shipping = WC()->shipping->calculate_shipping($packages);
$available_methods = WC()->shipping->get_packages();

$available_methods[0]['rates'] будет иметь все тарифы доставки, доступные для этого местоположения для продуктов внутри заказа.

2 голосов
/ 18 марта 2019

Попробуйте использовать:

// Calculate totals
WC()->cart->calculate_totals();
WC()->cart->calculate_shipping();

// Retrieve the shipping total
$shipping_total = WC()->cart->get_shipping_total();

Класс WC_Cart должен иметь все методы, необходимые для воссоздания любой функциональности корзины, которая может вам понадобиться. Я предлагаю вам прочитать и ознакомиться с определением класса здесь ...

https://docs.woocommerce.com/wc-apidocs/class-WC_Cart.html

...