1

我正在尝试找到一个功能,如果其中的产品高度超过 2,9 厘米,它会自动向购物车添加费用。

我将 Woocommerce 用于我们简单的非营利漫画书店。我们在瑞典使用基于重量的运输作为标准,如果某件物品超过 3 厘米,则会收取大量费用。

我已经尝试修改LoicTheAztec关于基于购物车总重量的费用的答案,但我真的不知道我在做什么,因为我在保存代码后得到一个空白页。

我要修改的代码是这样的:

add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 30, 1 );
function shipping_weight_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Convert cart weight in grams
    $cart_weight = $cart->get_cart_contents_weight() * 1000;
    $fee = 50; // Starting Fee below 500g

    // Above 500g we add $10 to the initial fee by steps of 1000g
    if( $cart_weight > 1500 ){
        for( $i = 1500; $i < $cart_weight; $i += 1000 ){
            $fee += 10;
        }
    }
    // Setting the calculated fee based on weight
    $cart->add_fee( __( 'Weight shipping fee' ), $fee, false );
}

我对 php 的体验不仅仅是能够将操作粘贴到我的子主题的 functions.php 中。

我很感激我能得到的任何帮助。

4

1 回答 1

2

如果任何购物车物品的高度不超过 3 厘米,以下代码将添加特定费用(Woocommerce 中的尺寸单位设置需要以厘米为单位)

add_action( 'woocommerce_cart_calculate_fees', 'shipping_height_fee', 10, 1 );
function shipping_height_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Your settings (here below)
    $height = 3; // The defined height in cm (equal or over)
    $fee    = 50; // The fee amount
    $found  = false; // Initializing

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        if( $cart_item['data']->get_height() >= $height ) {
            $found = true;
            break; // Stop the loop
        }
    }
    // Add the fee
    if( $found ) {
        $cart->add_fee( __( 'Height shipping fee' ), $fee, false );
    }
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。


补充:基于购物车物品总高度的代码:

add_action( 'woocommerce_cart_calculate_fees', 'shipping_height_fee', 10, 1 );
function shipping_height_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Your settings (here below)
    $target_height = 3; // The defined height in cm (equal or over)
    $total_height  = 0; // Initializing
    $fee           = 50; // The fee amount

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        $total_height += $cart_item['data']->get_height() * $cart_item['quantity'];
    }
    // Add the fee
    if( $total_height >= $target_height ) {
        $cart->add_fee( __( 'Height shipping fee' ), $fee, false );
    }
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

于 2019-02-25T17:45:15.307 回答