1

受此答案代码的启发,我们目前正在使用一些自定义代码,$2.50当数量相等时会增加美元费用6

但是,我们希望它$2.50在同一类别中的两个产品的数量分别为6.

它几乎可以工作,但是当同一类别中有两个产品并且其中一个具有一定数量时12,代码片段而不是保留$fee_amoutto $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 );
}
}
4

1 回答 1

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 文件中。测试和工作。

于 2018-08-21T02:53:59.903 回答