Бесплатная доставка в зависимости от веса и минимального количества корзины


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

Кто-нибудь знает, что мне следует делать?

Спасибо.

Author: LoicTheAztec, 2017-02-17

2 answers

Этот пользовательский код сохранит метод бесплатной доставки и скроет другие способы доставки, когда сумма в корзине достигнет 250 и если продукты не тяжелые (здесь менее 20 кг)… Чтобы запретить бесплатную доставку для заказов менее 250, вы можете установить это в woocommerce (см. В конце).

Сначала вам нужно будет убедиться, что вес установлен в каждом тяжелом продукте (для простых или переменных продуктов (в каждом варианте)). Промежуточный итог корзины здесь таков Без учета налогов ( и вы можете легко изменить его на Включение налогов).

enter image description here

Тогда вот эта пользовательская подключенная функция в woocommerce_package_rates крючок фильтра:

add_filter( 'woocommerce_package_rates', 'conditionally_hide_other_shipping_based_on_items_weight', 100, 1 );
function conditionally_hide_other_shipping_based_on_items_weight( $rates ) {

    // Set HERE your targeted weight (here is 20 kg) <== <== <== <== <==
    $target_product_weight = 20;

    // Set HERE your targeted cart amount (here is 250)  <== <== <== <== <==
    $target_cart_amount = 250;
    // 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 trough cart items to get the weight for each item
    foreach(WC()->cart->get_cart() as $cart_item){
        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);

        if( !empty($product_weight) && $product_weight >= $target_cart_amount ){
            $light_products_only = false;
            break;
        }
        else $light_products_only = true;
    }

    // If 'free_shipping' method is available and if products are not heavy
    // and cart amout up to the target limit, we hide other methods
    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id && $passed && $light_products_only ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }

    return ! empty( $free ) ? $free : $rates;
}

Вводится код function.php файл вашей активной дочерней темы (или темы) или также в любом файле плагина.

Этот код протестирован и работает для простых и переменных продуктов...

Вам также придется в настройках WooCommerce > Доставка для каждой доставки зоны и для "Free Shipping" способ определения минимальной суммы заказа:

enter image description here

Вам нужно будет обновить кэшированные данные доставки: отключить, сохранить и включить, сохранить соответствующие методы доставки для текущей зоны доставки в настройках доставки woocommerce.

 3
Author: LoicTheAztec, 2018-01-06 21:39:06

Для бесплатной доставки на определенную сумму вы можете использовать встроенную опцию WooCommerce.

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

 add_filter('woocommerce_package_rates', 'hide_shipping_method_if_particular_product_available_in_cart', 10, 2);

        function hide_shipping_method_if_particular_product_available_in_cart($available_shipping_methods)
        {
            global $woocommerce;

            // products_array should be filled with all the products ids
            // for which shipping method (stamps) to be restricted.

            $products_array = array(
                101,
                102,
                103,
                104
            );

            // You can find the shipping service codes by doing inspect element using
            // developer tools of chrome. Code for each shipping service can be obtained by
            // checking 'value' of shipping option.

            $shipping_services_to_hide = array(
                'free_shipping',

            );

            // Get all products from the cart.

            $products = $woocommerce->cart->get_cart();

            // Crawl through each items in the cart.

            foreach($products as $key => $item) {

                // If any product id from the array is present in the cart,
                // unset all shipping method services part of shipping_services_to_hide array.

                if (in_array($item['product_id'], $products_array)) {
                    foreach($shipping_services_to_hide as & $value) {
                        unset($available_shipping_methods[$value]);
                    }

                    break;
                }
            }

            // return updated available_shipping_methods;
    return
        }
 0
Author: Mujeebu Rahman, 2017-02-17 14:36:24