简体   繁体   中英

Cart fee based on specific product category cart item quantity in Woocommerce

Inspired by this answer code , we are currently using some custom code that adds a $2.50 dollar fee when the Quantity equals 6 .

However, we want it to add a $2.50 fee when two products in the same category have each a quantity of 6 .

It almost works, but when there are two products in the same category and one of them has a quantity of 12 then the code snippet instead of keeping the $fee_amout to $2.50 , changes it to $7.50 .

So we need to find a way to better target the individual products and their respective quantity or use or equation and -5 from it whenever it finds an instance of the product having a quantity of 12.

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 );
}
}

Updated

If I have well understood, you want to add a fixed cart fee, when there is 2 items from a specific product category in cart that have each one a quantity greater or equal to 6.

Try the following code:

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)
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM