Cart discount based on cart item count and only for items that are not in sale

前端 未结 1 975
萌比男神i
萌比男神i 2020-12-19 12:24

In WooCommerce, I would like to give a discount of 10% specifically for those products that are not on sale. If cart item count is 5 or more items and not on sale, then I gi

1条回答
  •  执笔经年
    2020-12-19 12:48

    Here is a custom hooked function that will apply to cart a discount, if there is 5 or more items in cart and no products on sale:

    add_action('woocommerce_cart_calculate_fees' , 'custom_discount', 10, 1);
    function custom_discount( $cart ){
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Only when there is 5 or more items in cart
        if( $cart->get_cart_contents_count() >= 5):
    
            // Initialising variable
            $is_on_sale = false;
    
            // Iterating through each item in cart
            foreach( $cart->get_cart() as $cart_item ){
                // Getting an instance of the product object
                $product =  $cart_item['data'];
    
                // If a cart item is on sale, $is_on_sale is true and we stop the loop
                if($product->is_on_sale()){
                    $is_on_sale = true;
                    break;
                }
            }
    
            ## Discount calculation ##
            $discount = $cart->subtotal * -0.1;
    
            ## Applied discount (no products on sale) ##
            if(!$is_on_sale )
                $cart->add_fee( '10% discount', $discount);
    
        endif;
    }
    

    This 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 perfectly.

    0 讨论(0)
提交回复
热议问题