Woocommerce расчет стоимости доставки на основе веса - PullRequest
1 голос
/ 07 марта 2019

В Woocommerce я хотел бы иметь функцию, которую я могу включить в свою тему, которая добавляет стоимость доставки на основе цены и веса.

  1. , если цена превышает 20 долларов США, доставка бесплатна, ниже доставкистоимость: 3USD
  2. , если вес превышает 10 кг. Стоимость доставки составляет 2USD дополнительно

На основе " Доставка рассчитывается исходя из веса товара и количества в корзине " ответить на тему, я пробовал что-то вроде следующего кода:

//Adding a custom Shipping Fee to cart based conditionally on weight and cart amount
add_action('woocommerce_cart_calculate_fees', 'custom_conditional_shipping_fee', 10, 1);
function custom_conditional_shipping_fee( $cart_object ){

    #### SETTINGS ####

    // Your targeted "heavy" product weight
    $target_weight = 1;

    // Your targeted cart amount
    $target_cart_amount = 20;

    // Price by Kg;
    $price_kg = 2;

    // Amount set in 'flat rate' shipping method;
    $flat_rate_price;


    // Initializing variables
    $fee = 0;
    $calculated_weight = 0;

    // For cart SUBTOTAL amount EXCLUDING TAXES
    WC()->cart->subtotal_ex_tax >= $target_cart_amount ? $passed = true : $passed = false ;

    // For cart SUBTOTAL amount INCLUDING TAXES (replace by this):
    // WC()->cart->subtotal >= $target_cart_amount ? $passed = true : $passed = false ;

    // Iterating through each cart items
    foreach( $cart_object->get_cart() as $cart_item ){

        // Item id ($product ID or variation ID)
        if( $cart_item['variation_id'] > 0)
            $item_id = $cart_item['variation_id'];
        else
            $item_id = $cart_item['product_id'];

        // Getting the product weight
        $product_weight = get_post_meta( $item_id , '_weight', true);

        // Line item weight
        $line_item_weight = $cart_item['quantity'] * $product_weight;

        // When cart amount is up to 1kg, Adding weight of heavy items
        if($passed && $product_weight < $target_weight)
            $calculated_weight += $line_item_weight;
    }

    #### Making the fee calculation ####

    // Cart is up to 250 with heavy items
    if ( $passed && $calculated_weight != 0 ) {
        // Fee is based on cumulated weight of heavy items
        $fee = ($calculated_weight * $price_kg) - $flat_rate_price;
    }
    // Cart is below 250
    elseif ( !$passed ) {
        // Fee is based on cart total weight
        $fee = ($cart_object->get_cart_contents_weight( ) * $price_kg) - $flat_rate_price;
    }

    #### APPLYING THE CALCULATED FEE ####

    // When cart is below 250 or when there is heavy items
    if ($fee > 0){
        // Rounding the fee
        $fee = round($fee);
        // This shipping fee is taxable (You can have it not taxable changing last argument to false)
        $cart_object->add_fee( __('Shipping weight fee', 'woocommerce'), $fee, true);
    }
}

Редактировать:

И в то же время я хочу, чтобы это показывалосьэто сразу на странице корзины.Теперь он показывает «введите адрес для просмотра вариантов доставки».В основном просто посмотрите на общую сумму корзины и покажите либо тариф, либо бесплатную доставку на основе правил, описанных для веса и цены.

enter address to view shipping options

Ответы [ 2 ]

0 голосов
/ 07 марта 2019

Следующий код основан не на пользовательской плате, а на настройке методов доставки. Требуется установить в настройках доставки для каждой зоны доставки:

  • «Фиксированная ставка» с определенной стоимостью ($3 для вас)
  • «Бесплатная доставка» без требований (без ограничений) .

Код будет обрабатывать стоимость расчета фиксированной ставки на основе веса , а также налоговые расчеты .

Код будет работать для любой зоны доставки без необходимости определения в коде идентификаторов методов доставки.

Вот код:

add_filter( 'woocommerce_package_rates',  'filter_package_rates_callback', 10, 2 );
function filter_package_rates_callback( $rates, $package ) {

    ## -------- Settings -------- ##
    $targeted_total   = 20; // The targeted cart amount
    $weight_threshold = 10; // The cart weight threshold
    $extra_for_10kg   = 2;  // 10 Kg addition extra cost;

    $total_weight    = WC()->cart->get_cart_contents_weight();
    $cart_subtotal   = WC()->cart->get_subtotal(); // Excluding taxes

    // Set shipping costs based on weight
    foreach ( $rates as $rate_key => $rate ){
        $has_taxes = false;

        if( $cart_subtotal < $targeted_total || $total_weight >= $weight_threshold ){
            // Remove Free shipping Method
            if( 'free_shipping' === $rate->method_id ) {
                unset( $rates[$rate_key] );
            }
            // Flat rate calculation cost when 10 kg weight is reached
            if( 'flat_rate' === $rate->method_id && $total_weight >= $weight_threshold ) {
                // The default rate cost (set in the shipping method)
                $default_cost = $rate->cost; 

                // The new calculated cost (up to 10 kg)
                $new_cost = $default_cost + $extra_for_10kg; 

                // Tax rate conversion (for tax calculations)
                $tax_rate_converion = $new_cost / $default_cost;

                // Set the new cost
                $rates[$rate_key]->cost = $new_cost;

                // TAXES RATE COST (if enabled)
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $tax > 0 ){
                        // New tax calculated cost
                        $taxes[$key] = $tax * $tax_rate_converion; 
                        $has_taxes = true;
                    }
                }
                // Set new taxes cost
                if( $has_taxes )
                    $rates[$rate_key]->taxes = $taxes;
            }
        } else {
            // Remove Flat Rate methods (keeping Free Shipping Method only)
            if( 'flat_rate' === $rate->method_id ) {
                unset( $rates[$rate_key] );
            }
        }
    }
    return $rates;
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы). Проверено и работает.

Обновите кэши доставки: (обязательно)
1) Этот код уже сохранен в вашем файле function.php.
2) В настройках зоны доставки отключите / сохраните любой способ доставки, затем включите обратно / сохранить.
Вы сделали , и вы можете проверить это.


Отображение способов доставки напрямую (Относительно вашего вопроса отредактировать)

Предоставленной информации в вашем вопросе недостаточно, чтобы увидеть, как это можно сделать.

Если вы продаете в одной стране , и у вас есть уникальная зона доставки, вы можете заставить страну для незарегистрированных клиентов отображать способы доставки, используя следующее:

add_action( 'template_redirect', 'allow_display_shipping_methods' );
function allow_display_shipping_methods() {
    // HERE define the targeted country code
    $country_code = 'GB';

    // Set the shipping country if it doesn't exist
    if( ! WC()->customer->get_shipping_country() )
        WC()->customer->set_shipping_country('GB');
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы). Проверено и работает.

Теперь это другой вопрос , в вашем первоначальном вопросе , и его следует задать как новый вопрос .


Похожие ответы:

0 голосов
/ 07 марта 2019

woocommerce_package_rates - это правильный фильтр для настройки скорости доставки.

Этого можно добиться следующим образом.

Шаг 1: Создайте два способа доставки, Бесплатная доставка и Фиксированная ставка с побережьем 3 $

Шаг 2: Скопируйте и вставьте приведенный ниже фрагмент кода в functions.php

Правильно настройте фиксированную ставку и бесплатную доставкуво фрагменте.

add_filter( 'woocommerce_package_rates',  'modify_shipping_rate', 15, 2 );
function modify_shipping_rate( $available_shipping_methods, $package ){

    global $woocmmerce;
    $total_weight = WC()->cart->cart_contents_weight;
    $total_coast = WC()->cart->get_cart_contents_total();


    if( $total_coast >= 20 ){
        unset($available_shipping_methods['flat_rate:1']); //Remove flat rate for coat abobe 20$
    }elseif( $total_weight > 10 ){
        unset($available_shipping_methods['free_shipping:1']); // remove free shipping for below 20$ 
        $available_shipping_methods['flat_rate:1']->cost += 2; // add 2$ if weight exceeds 10KG
    }else{
        unset($available_shipping_methods['free_shipping:1']); // remove free shipping for below 20$ 
    }

    return $available_shipping_methods;
}

Используйте приведенный ниже фрагмент, чтобы изменить сообщение о корзине по умолчанию.

add_filter( 'woocommerce_cart_no_shipping_available_html', 'change_msg_no_available_shipping_methods', 10, 1  );
add_filter( 'woocommerce_no_shipping_available_html', 'change_msg_no_available_shipping_methods', 10, 1 );
function change_msg_no_available_shipping_methods( $default_msg ) {

    $custom_msg = "Enter address to view shipping options";
    if( empty( $custom_msg ) ) {
      return $default_msg;
    }

    return $custom_msg;
}
...