Можно ли предоставить скидку на стоимость доставки при оформлении заказа в WooCommerce? - PullRequest
0 голосов
/ 26 июня 2019

Мы хотим предоставить нашим клиентам скидку в зависимости от стоимости доставки (50% от стоимости доставки).Ниже приведен код для управления скидкой, все в порядке, но я не могу получить стоимость доставки.Пробовал php $current_shipping_cost = WC()->cart->get_cart_shipping_total();, но он не возвращает правильное значение.Есть ли способ сделать это?

function woocommerce_coupon_get_discount_amount($discount, $discounting_amount, $cart_item, $single, $coupon) { 

        if ($coupon->code == 'custom'){

            /*It is needed to know the shipping cost to calculate the discount. 
            $current_shipping_cost = WC()->cart->get_cart_shipping_total();
echo $current_shipping_cost; is not returning the correct value.
            */
             return $discount;
            }
        }
//add hook to coupon amount hook
add_filter('woocommerce_coupon_get_discount_amount', 'woocommerce_coupon_get_discount_amount', 100, 5);

Ответы [ 4 ]

0 голосов
/ 26 июня 2019

Это может помочь вам со скидкой.

add_action('woocommerce_cart_calculate_fees','woocommerce_discount_for_shipping' );
function woocommerce_discount_for_shipping()
{
    global $woocommerce;
    //$discount_cart = $cart->discount_cart;
    $shipping_including_tax = $woocommerce->cart->shipping_total + $woocommerce->cart->shipping_tax_total;
    $percentage = 0.5;
    $discount = $shipping_including_tax * $percentage;
    //var_dump($discount);
    $woocommerce->cart->add_fee('Shipping Discount:', -$discount, false);
}
0 голосов
/ 26 июня 2019

@ László T , вы можете использовать следующий код, чтобы получить стоимость доставки.см. код я дал 50% скидку от стоимости доставки.Это работает для меня.

function woocommerce_coupon_get_discount_amount($discount, $discounting_amount, $cart_item, $single, $coupon) {
    if ($coupon->code == 'ship_discount'){  // ship_discount is coupon code
        $shipping_cost = 0;
        foreach( WC()->session->get('shipping_for_package_0')['rates'] as $method_id => $rate ){
            $shipping_cost += $rate->cost; // calculate  shipping cost
        }
        return  $shipping_cost/2;  //shipping cost to calculate the discount
    }
}
add_filter('woocommerce_coupon_get_discount_amount', 'woocommerce_coupon_get_discount_amount', 10, 5);

Я надеюсь, что это может быть полезно для вас.

Спасибо

0 голосов
/ 26 июня 2019

Следующий код установит стоимость доставки в 50% для метода доставки «Единый тариф», когда в товарах корзины найден определенный определенный способ доставки.

Настройки доставки "Единый тариф": необходимо определить стоимость классов доставки.

add_filter('woocommerce_package_rates', 'shipping_costs_discounted_based_on_shipping_class', 10, 2);
function shipping_costs_discounted_based_on_shipping_class( $rates, $package ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return $rates;

    // Your settings bellow
    $shipping_class = 'large'; // <=== Shipping class slug
    $percentage     = 50; //      <=== Discount percentage

    $discount_rate  = $percentage / 100;
    $is_found       = false;

    // Loop through cart items and checking for the specific defined shipping class
    foreach( $package['contents'] as $cart_item ) {
        if( $cart_item['data']->get_shipping_class() == $shipping_class )
            $is_found = true;
    }

    // Set shipping costs to 50% if shipping class is found
    if( $is_found ){
        foreach ( $rates as $rate_key => $rate ){
            $has_taxes = false;
            // Targeting "flat rate"
            if( 'flat_rate' === $rate->method_id  ){
                $rates[$rate_key]->cost = $rate->cost * $discount_rate;

                // Taxes rate cost (if enabled)
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $tax > 0 ){
                        $has_taxes = true;
                        $taxes[$key] = $tax * $discount_rate;
                    }
                }
                if( $has_taxes )
                    $rates[$rate_key]->taxes = $taxes;
            }
        }
    }
    return $rates;
}

вот полный референс Стоимость доставки скидка на основе классов доставки в Woocommerce

0 голосов
/ 26 июня 2019

Используйте "woocommerce_after_calculate_totals" крючок.Это дает вам объект корзины на кассе или странице корзины.Вы можете получить как общую сумму доставки, так и общую сумму налога, если ваш сайт использует налоги.

$cart->shipping_total;
$cart->shipping_tax_total;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...