【问题标题】:Add a fee based on cart items dimensions in Woocommerce根据 Woocommerce 中的购物车商品尺寸添加费用
【发布时间】:2020-01-17 08:18:21
【问题描述】:

2 月份我在这里得到了很大的帮助,关于 woocommerce 问题,我需要根据购物车总高度自动添加费用,in this thread。

现在,我还需要在代码中添加对项目宽度的计算。但前提是购物车中的任何物品的宽度超过 25 厘米(不是总宽度,因为产品是堆叠在一起的书籍,所以额外的运费按总高度和宽度超过 25 厘米计算) . 例子:

实际效果如何:

  • 如果购物车的总高度为 3 厘米或以上,则需要付费。

需要什么(补充):

  • 如果一件物品的宽度超过 25 厘米,则需要付费。
  • 如果购物车的总高度为 3 厘米或以上,并且如果一件商品的宽度超过 25 厘米,则需要付费。

我一直在玩 "Add a fee based on cart items height in Woocommerce" 答案代码(第二个代码 sn-p),试图向它添加一个高度变量($target_width = 25; // ),但是我在计算中迷失了方向,不知道如何尝试它而不使其成为总车宽,我只是没有资格对代码进行如此高级的编辑。我所有的不同尝试都没有奏效。

感谢我能得到的任何帮助。

【问题讨论】:

  • 代码已更新: 将缺失的 ; 添加到 $width_threshold = 25...

标签: php wordpress woocommerce cart fee


【解决方案1】:

更新:以下代码将处理您有要求的额外物品,如果物品宽度超过 25 厘米,也会收取费用:

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

    // Your settings (here below)
    $target_height   = 3; // The defined height in cm (equal or over)
    $width_threshold = 25; // The defined item with to set the fee.
    $fee             = 50; // The fee amount

    // Initializing variables
    $total_height    = 0; 
    $apply_fee       = false;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        // Calculating total height
        $total_height += $cart_item['data']->get_height() * $cart_item['quantity'];

        // Checking item with
        if ( $cart_item['data']->get_width() > $width_threshold ) {
            $apply_fee = true;
        }
    }

    // Add the fee
    if( $total_height >= $target_height || $apply_fee ) {
        $cart->add_fee( __( 'Dimensions shipping fee' ), $fee, false );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件中。它应该可以工作。

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多