Пользовательские расчетные расходы на доставку в зависимости от класса доставки в WooCommerce - PullRequest
1 голос
/ 01 апреля 2019

После обновления Woocommerce до последней версии 3.5.7 прошлой ночью, оформление заказа останавливается, если страна переключается из США в Канаду на странице оформления заказа. Если мы вернемся к странице корзины, появится сообщение об ошибке. Детали ошибки находятся в конце этого вопроса. Что может быть причиной этого? Я также скопировал фрагмент кода ниже, который приводит к этой ошибке. В частности, строка $label = $method->get_label();, но я не вижу никаких проблем с этим.

Что я уже тестировал:
1- Я сначала подумал, что использование скобок на этикетках для доставки не работает, но это не проблема, уже протестированная на демонстрационном сайте.
2- Это происходит только в том случае, если в корзине указан определенный способ доставки, а в случае других способов доставки это не так, как показано на приведенном ниже скриншоте.


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

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

Запись экрана:
https://screencast -o-matic.com / watch / cqfVoTZckd

Код внутри cart-shipping.php, вызывающий проблему:

foreach ( $available_methods as $method ) : ?> 
                    <li>
                        <?php
                            $a = (int)$method->cost;
                            $b = $method->id;
                            $label = $method->get_label(); /* this line is causing the error but I don't see any issue with it */
                            if ($a === 0 && $b != "legacy_local_pickup"):
                                printf( '<input type="radio" name="shipping_method[%1$d]" data-index="%1$d" id="shipping_method_%1$d_%2$s" value="%3$s" class="shipping_method" %4$s />
                                <label for="shipping_method_%1$d_%2$s">Standard (Ships in 10-12 work days): <span class="woocommerce-Price-amount amount">Free</span></label>',
                                $index, sanitize_title( $method->id ), esc_attr( $method->id ), checked( $method->id, $chosen_method, false ) );
                            elseif ($b == "legacy_local_pickup"):
                                printf( '<input type="radio" name="shipping_method[%1$d]" data-index="%1$d" id="shipping_method_%1$d_%2$s" value="%3$s" class="shipping_method" %4$s />
                                <label for="shipping_method_%1$d_%2$s">%5$s</label>',
                                $index, sanitize_title( $method->id ), esc_attr( $method->id ), checked( $method->id, $chosen_method, false ), $label );    
                            else:
                                printf( '<input type="radio" name="shipping_method[%1$d]" data-index="%1$d" id="shipping_method_%1$d_%2$s" value="%3$s" class="shipping_method" %4$s />
                                <label for="shipping_method_%1$d_%2$s">%5$s</label>',
                                $index, sanitize_title( $method->id ), esc_attr( $method->id ), checked( $method->id, $chosen_method, false ), wc_cart_totals_shipping_method_label( $method ) );   
                            endif;

                            do_action( 'woocommerce_after_shipping_rate', $method, $index );
                        ?>
                    </li>
                <?php endforeach; 

Ошибка:

Fatal error: Uncaught Error: Call to undefined method stdClass::get_label() in .../themes/genesis-sample/woocommerce/cart/cart-shipping.php:35 Stack trace: #0 .../plugins/woocommerce/includes/wc-core-functions.php(211): include() #1 .../plugins/woocommerce/includes/wc-cart-functions.php(233): wc_get_template('cart/cart-shipp...', Array) #2 .../plugins/woocommerce/templates/cart/cart-totals.php(48): wc_cart_totals_shipping_html() #3 .../plugins/woocommerce/includes/wc-core-functions.php(211): include('...') #4 .../plugins/woocommerce/includes/wc-template-functions.php(1922): wc_get_template('cart/cart-total...') #5 .../wp-includes/class-wp-hook.php(286): woocommerce_cart_totals('') in .../themes/genesis-sample/woocommerce/cart/cart-shipping.php on line 35

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

После тестирования на промежуточной площадке я нашел реальную причину. Вот кусок кода, создающий проблемы. Проблема в том, что $method_id5 доступен только для США, а не для Канады, поэтому, когда клиент переключается на Канаду, эта часть кода выходит из строя. Для Канады доступный способ доставки: $method_id6 = 'flat_rate:6';:

add_filter( 'woocommerce_package_rates', 'change_shipping_method_rate_based_on_shipping_class_2', 11, 2 );

function change_shipping_method_rate_based_on_shipping_class_2( $rates, $package ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping class to find
    $class = array(206);

    // HERE define the shipping method to change rates for
    $method_id5 = 'flat_rate:5';

    // Checking in cart items
    $found = false;
    $item_price = $item_qty = $rush_fee = 0;
    foreach( WC()->cart->get_cart() as $cart_item ){
        $item_shipping_class_id = $cart_item['data']->get_shipping_class_id();


        if( in_array( $item_shipping_class_id, $class ) ){
            $found = true;  // Target shipping class found
            $item_price += $cart_item['data']->get_price(); // Sum line item prices that have target shipping class
            $item_qty += $cart_item['quantity']; // Sum line item prices that have target shipping class
            $item_total = $item_price * $item_qty;
            $rush_fee = $item_total * 0.2;
        } 
    }

    if( $found ) {
        if( $item_total > 0 && $item_total < 200 ) {
            if($rush_fee < 25) {
                $rates[$method_id5]->cost = 25 + 18.99;
            } else {
                $rates[$method_id5]->cost = $rush_fee + 18.99;
            }
        }
        elseif ( $item_total > 200 ) {
            if($rush_fee < 25) {
                $rates[$method_id5]->cost = 25;
            } else {
                $rates[$method_id5]->cost = $rush_fee;
            }
        }
    }
    return $rates;
}

Есть мысли по этому поводу?

1 Ответ

1 голос
/ 01 апреля 2019

Обновление № 1: (на основе вашего 2-го редактирования)

Попробуйте вместо этого следующее:

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

    // HERE define your shipping class to find
    $class = array(206);

    // HERE define the shipping method to change rates for
    $shipping_rate_ids = array('flat_rate:5', 'flat_rate:6')

    // Initialising
    $found = false;
    $item_price = $item_qty = $rush_fee = $item_total = 0;

    // Loop through cart items
    foreach( $package['contents'] as $cart_item_key => $cart_item ) {
        $item_shipping_class_id = $cart_item['data']->get_shipping_class_id();

        if( in_array( $item_shipping_class_id, $class ) ){
            $item_price += $cart_item['data']->get_price(); // Sum line item prices that have target shipping class
            $item_qty += $cart_item['quantity']; // Sum line item prices that have target shipping class
            $item_total = $item_price * $item_qty;
            $rush_fee = $item_total * 0.2;
            $found = true;  // Target shipping class found
        } 
    }

    if( $found ) {
        // Loop through shipping rates
        foreach( $rates as $rate_key => $rate ) {
            if( in_array($rate_key, $shipping_rate_ids) ) {
                if( $item_total > 0 && $item_total < 200 ) {
                    if($rush_fee < 25) {
                        $rates[$rate_key]->cost = 25 + 18.99;
                    } else {
                        $rates[$rate_key]->cost = $rush_fee + 18.99;
                    }
                }
                elseif ( $item_total > 200 ) {
                    if($rush_fee < 25) {
                        $rates[$rate_key]->cost = 25;
                    } else {
                        $rates[$rate_key]->cost = $rush_fee;
                    }
                }
            }
        }
    }
    return $rates;
}

Код включается функциейФайл .php вашей активной дочерней темы (или темы).Протестировано и работает.

Обновление кэшей доставки: (обязательно)

  1. Этот код уже сохранен на вашем активномфайл theme.php темы.
  2. Корзина пуста
  3. В настройках зоны доставки отключите / сохраните любой способ доставки, затем включите обратно / сохраните.

Первоначальный ответ.

Поскольку $method является экземпляром stdClass, а не экземпляром WC_Shipping_Rate, метод get_label() не определен дляэто (не существует) . Вместо этого вы можете использовать свойство label.

Так что вам просто нужно заменить в шаблоне:

$label = $method->get_label();

На

$label = $method->label; 

Это должно остановить эту ошибку и решить вашу проблему.

...