Установите стоимость доставки в зависимости от класса доставки в Woocommerce.

Мы продаем образцы продуктов на нашем сайте Woocommerce, который является всего лишь переменным продуктом. Товар имеет уникальный класс доставки, который позволяет его доставить за 1,99.

Фактически эта стоимость всегда устанавливается, если товар принадлежит этому уникальному классу доставки, даже если есть другие товары.

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

Любая помощь приветствуется.


person Meds    schedule 03.09.2018    source источник


Ответы (1)


Следующая подключенная функция установит стоимость доставки равной 0, если товары с определенным классом доставки объединяются с другими товарами:

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

    // HERE define the targeted shipping method
    $shipping_class = 'Extra';

    // Initializing variables
    $found = $others = false;

    // Loop through cart items and checking for the specific product
    foreach( $package['contents'] as $item ) {
        if( $item['data']->get_shipping_class() == sanitize_title($shipping_class) ){
            $found = true; // Has the shipping class
        } else {
            $others = true; // NOT the shipping class
        }
    }

    // When items with the defined shipping are not alone in cart
    if( $found && $others ){
        // Loop through shipping rates
        foreach ( $rates as $rate_key => $rate ){
            // For Flat rate and Local pickup shipping methods
            if( $rate->method_id == 'flat_rate' ) {
                // Set the cost to zero
                $rates[$rate_key]->cost = 0;

                $rates[$rate_key]->label = 'f: '.$found.' | o: '.$others.' ';

                // Initializing variables
                $has_taxes = false;
                $taxes = [];

                // Loop through the shipping taxes array (as they can be many)
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $rates[$rate_key]->taxes[$key] > 0 ){
                        // Set the tax cost to zero
                        $taxes[$key] = 0;
                        $has_taxes   = true;
                    }
                }
                // Set new taxes cost array
                if( $has_taxes )
                    $rates[$rate_key]->taxes = $taxes;
            }
        }
    }

    return $rates;
}

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

person LoicTheAztec    schedule 03.09.2018