2
votes

I have one little problem that dont know how to fix myself. I want to use this logic into my Woocommerce store just for one product.

I have use link like this to autmatically apply coupon code and add to cart:

https://testsite.com/checkout/?add-to-cart=Product_ID&quantity=1&coupon=Coupon_Code

and this seems to work, when quantity is 1. But i want discount (30%) that is automatically placed when click on direct link from before, to make dynamic, for ex:

  • Increase quantity to 2 in cart page, and coupon automatically to calculate 2 x 30$ = 60$ discount,
  • buy 3 from same product, and calculate 3 X 30$ = 90$ coupon discount and so on..

I searched, and found this usefull thread, but there situation is little different then mine.

How can I make to have a specific coupon? Some advice or start point. Thanks

1

1 Answers

1
votes

This is possible with that 2 steps:

1) Add a unique coupon with:

  • In General settings > Type = Fixed Product discount
  • In General settings > Amount = 30
  • In Usage restrictions > Products ==> set your desired product(s)

2) Add this code (where you will set your coupon code in the function (in lowercase)):

add_filter( 'woocommerce_coupon_get_discount_amount', 'custom_coupon_get_discount_amount', 10, 5 );
function custom_coupon_get_discount_amount( $rounded_discount, $discounting_amount, $cart_item, $single, $coupon ){

    ## ---- Your settings ---- ##

    // Related coupons codes to be defined in this array (you can set many)
    $coupon_codes = array('30perqty');

    ## ------ The code ------- ##

    if ( $coupon->is_type('fixed_product') && in_array( $coupon->get_code(), $coupon_codes ) && $cart_item['quantity'] > 1 ) {
        if( in_array( $cart_item['product_id'], $coupon->get_product_ids() ) ){
            $discount = (float) $coupon->get_amount() * (int) $cart_item['quantity'];
            $round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() );
        }
    }
    return $rounded_discount;
}

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