Auto apply or remove a coupon in Woocommerce cart for a specific product id

后端 未结 1 436
情歌与酒
情歌与酒 2021-01-22 11:02

I am applying automatically a coupon when there is a product id 1362 in the cart, but when someone adds another product and delete the 1362 the coupon stays applied, how to prev

1条回答
  •  借酒劲吻你
    2021-01-22 11:48

    Here is the way to make it work when:

    • adding a specific coupon code when a specific product is added to cart
    • removing a specific applied coupon code when a specific product is removed from cart
    • (in both cases you can display a custom notice)…

    The code:

    add_action( 'woocommerce_before_calculate_totals', 'auto_add_remove_coupon' );
    function auto_add_remove_coupon( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        $coupon_code = 'boxpersonnalisable';
        $targeted_product_ids = array( 1362 );
        $found = false;
    
        // Loop through cart items
        foreach ( $cart->get_cart() as $cart_item ){
            if( in_array( $cart_item['product_id'], $targeted_product_ids ) ){
                $found = true;
                break;
            }
        }
    
        if ( ! $cart->has_discount( $coupon_code ) && $found ) {
            $cart->add_discount( $coupon_code );
            wc_clear_notices();
            wc_add_notice( __("Your custom notice - coupon added (optional)","woocommerce"), 'notice');
        } elseif  ( $cart->has_discount( $coupon_code ) && ! $found ) {
            $cart->remove_coupon( $coupon_code );
            wc_clear_notices();
            wc_add_notice( __("Your custom notice - coupon removed (optional)","woocommerce"), 'notice');
        }
    }
    

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

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