I'm looking for a way to create a coupon programmatically during the checkout and delete it when the checkout is done. This needs to be done base on a bonus system where I check if the customer is allowed to have a bonus or not. The important thing is, that I don't want to make it as a normal coupon because customers shouldn't be able to append it by there own knowing the code.
I've only found solution to append a coupon or create it programmatically. I've found nothing about a temporary coupon during one checkout.
It's also important that this coupon can be combined with just one another coupon and not more.
This is my code:
if ( get_discount_points() < 100 ) {
//Customer has bonus status 1
} elseif ( get_discount_points() < 200 ) {
//Customer has bonus status 2
} else {
//Customer has bonus status x
by the discount percentage }
So is this even possible?
To get something simple you could use a negative fee instead (where each step points increase the discount percentage) like:
function get_customer_discount(){
if( $points = get_discount_points() ){
if ( $points < 100 ) {
return 1; // 1 % discount
} elseif ( $points < 200 ) {
return 2; // 2.5 % discount
} else {
return 4; // 5 % discount
}
} else {
return false;
}
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_discount', 10, 1 );
function custom_discount( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only for 2 items or more
if( $percentage = get_customer_discount() ){
$discount = WC()->cart->get_subtotal() * $percentage / 100;
// Apply discount to 2nd item for non on sale items in cart
if( $discount > 0 )
$cart->add_fee( sprintf( __("Discount %s%%"), $percentage), -$discount );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With