在Woocommerce中根据购物车商品尺寸添加费用 [英] Add a fee based on cart items dimensions in Woocommerce

查看:180
本文介绍了在Woocommerce中根据购物车商品尺寸添加费用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I got great help here in February, regarding a woocommerce issue where I needed an automatic fee added based on total cart height, in this thread.

现在,我还需要在代码中添加关于商品宽度的计算.但是,只有当购物车中的任何物品的宽度超过25厘米时(由于产品是相互叠放的书本,因此总宽度不是总宽度,因此额外的运输费用是根据25厘米以上的总高度和宽度计算的) . 例子:

Now, I also need to add a calculation on item width to the code. But only if any of the items in the cart have a width over 25 cm (not total width since the products are books that are stacked on top of each other, so the extra shipping fees are calculated on total height and width over 25 cm). Examples:

实际上在做什么:

  • 如果推车的总高度为3厘米或以上,则将收取一定费用.

还需要什么:

  • 如果一件商品的宽度超过25厘米,则将收取费用.
  • 如果购物车的总高度为3厘米或以上,并且一件商品的宽度超过25厘米,则将收取费用.

我一直在玩"答案代码(第二个代码段),并尝试向其添加一个高度变量($ target_width = 25;//) ,但我迷失在计算中,不知道如何在不使购物车总宽度变大的情况下进行尝试,而且我不具备执行此类高级代码的资格.我所有的尝试都没有用.

I've been playing around with "Add a fee based on cart items height in Woocommerce" answer code (2nd code snippet), trying to add a height variable to it ($target_width = 25; // ), but I get lost in the calculation, not knowing how to try it without it becoming total cart width and I'm just not qualified to do such an advanced editing of code. All my different attempts didn't work.

感谢我可以获得的任何帮助.

Appreciate any help I can get.

推荐答案

已更新:以下代码将根据需要处理您的其他商品,如果商品宽度超过25厘米,还将收取费用:

Updated: The following code will handle your additional item with requirement, applying also the fee if a item width is over 25 cm:

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文件中.应该可以.

Code goes in function.php file of your active child theme (or active theme). It should works.

这篇关于在Woocommerce中根据购物车商品尺寸添加费用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆