首页 > 解决方案 > Woocommerce, set shipping class based on cart item quantity

问题描述

Hi im trying to set different shipping classes in the cart dependent on how many items there are in the cart. I have tried to make this work by adding the following to functions.php.

//Set shipping class based on item quantity
add_action( 'woocommerce_cart_calculate_fees', 'shipping_class_and_item_quantity'); 
function shipping_class_and_item_quantity( $cart ) {

    $shipping_class_one = '1-6-flaskor';
    $shipping_class_two = '7-12-flaskor';

    foreach( $cart->get_cart() as $cart_item ) {
        $product = $cart_item['data'];

        if( $cart_item['quantity'] >= 6 ) {
            $product->get_shipping_class() == $shipping_class_one;
        }else if( $cart_item['quantity'] >= 12 ){
            $product->get_shipping_class() == $shipping_class_two;
        }
    }
}

found something similar online, which I've been trying to reverse engineer, but it doesn't seem to work, most likely due to my limited php skills. Very thankful for any help.

标签: phpwoocommerce

解决方案


我重新阅读了你的问题。像这样的东西会起作用吗?

function custom_shipping_cost_tiers( $cost, $method ) {
    $methodlabel = 'Enter the name of your method here' ie 'Flat Rate';

    if ($method->get_label() == $methodlabel) {
        $cart_item_count = WC()->cart->get_cart_contents_count();

        if ( $cart_item_count >= 6) {
            $cost = *SET FEE HERE*;
        }
        else if ( $cart_item_count >= 12){
            $cost = *SET FEE HERE*;
        }
    return $cost;
    }
 }

add_filter( 'woocommerce_shipping_rate_cost', 'custom_shipping_cost_tiers', 10, 2 );

这应该可以满足您的需求。


推荐阅读