【问题标题】:Cart fee based on specific product category cart item quantity in Woocommerce基于 Woocommerce 中特定产品类别购物车项目数量的购物车费用
【发布时间】:2018-08-20 19:48:13
【问题描述】:

this answer code 的启发,我们目前正在使用一些自定义代码,当数量等于6 时会添加$2.50 美元费用。

但是,当同一类别中的两个产品每个都有6的数量时,我们希望它增加$2.50费用。

它几乎可以工作,但是当同一类别中有两个产品并且其中一个的数量为 12 时,代码 sn-p 而不是保留 @987654327 @$2.50,将其更改为 $7.50

因此,我们需要找到一种方法来更好地定位单个产品及其各自的数量或用途或方程式,并在找到数量为 12 的产品实例时从中得到 -5。

function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

// Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
$categories = array('649');
$fee_amount = 0;
$cat_count = 0; 

// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {

    if( has_term( $categories, 'product_cat', $cart_item['product_id']))
        $quantity = $cart_item['quantity'];
    $cat_count += $cart_item['quantity'];

}


if ($quantity == 6){
$fee_amount = (2.5 * ($cat_count/6));
;}  

// Adding the fee
if ( $fee_amount > 0 ){
    // Last argument is related to enable tax (true or false)
    WC()->cart->add_fee( __( "Find-it Mixed Case", "woocommerce" ), $fee_amount, false );
}
}

【问题讨论】:

    标签: php wordpress woocommerce cart fee


    【解决方案1】:

    更新

    如果我很好理解,当购物车中有 2 件来自特定产品类别的商品且每件商品的数量大于或等于 6 时,您想添加固定的购物车费用。

    试试下面的代码:

    add_action( 'woocommerce_cart_calculate_fees', 'custom_cart_fee', 20, 1 );
    function custom_cart_fee( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
        $categories  = array('649');
    
        // Initializing
        $count = 0;
    
        // Loop through cart items
        foreach( $cart->get_cart() as $cart_item ) {
            if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                if( $cart_item['quantity'] >= 6 ){
                    $count++;
                }
            }
        }
    
        if ( $count >= 1 ) {
            $fee_amount = 2.50 * $count;
            $cart->add_fee( __( "Shipping fee", "woocommerce" ), $fee_amount, false );
            // Last argument is related to enable tax (true or false)
        }
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

    【讨论】:

    • 嘿,这真的很接近,但我们正在寻找的是每次有人订购固定数量为 6 的同一类别的产品时增加 2.50 美元的代码。所以如果两个人订购了 6 个产品作为数量,费用应等于 5.00 美元。
    • 谢谢你回答了我的问题。
    猜你喜欢
    • 2019-12-19
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多