Custom discount for every NTH item in the cart

て烟熏妆下的殇ゞ 提交于 2021-01-28 08:04:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!