问题
I came here from this question here looking to find a solution for my WooCommerce site. I am looking for a way to get a discount in my cart only for even number of items in the cart.
For example:
If there's only 1 item in the cart: Full Price
2 Items in the cart: - (minus) 2$ for both of it
5 Items in the cart: - (minus) 2$ for 4 of it (if there's odd number of items in the cart. 1 item will always have the full price)
By the way, all of my products are having the same price.
Would someone be able to help me on this, as someone helped for the guy on the question link I've mentioned?
回答1:
Here is your custom function hooked in woocommerce_cart_calculate_fees
action hook, that will do what you are expecting:
add_action( 'woocommerce_cart_calculate_fees','cart_conditional_discount', 10, 1 );
function cart_conditional_discount( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_count = 0;
foreach($cart_object->get_cart() as $cart_item){
// Adds the quantity of each item to the count
$cart_count += $cart_item["quantity"];
}
// For 0 or 1 item
if( $cart_count < 2 ) {
return;
}
// More than 1
else {
// Discount calculations
$modulo = $cart_count % 2;
$discount = (-$cart_count + $modulo);
// Adding the fee
$discount_text = __('Discount', 'woocommerce');
$cart_object->add_fee( $discount_text, $discount, false );
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.
来源:https://stackoverflow.com/questions/43333443/custom-discount-for-every-nth-item-in-the-cart