在 Woocommerce 中根据购物车商品高度添加费用

Add a fee based on cart items height in Woocommerce

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

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

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

我要修改的代码是这个:

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  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 中。

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

如果任何购物车商品的高度不超过 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 文件。已测试并有效。