READ FIRST: This code needs to be added at the end of the functions.php file. If you are familiar with editing functions.php, feel free to continue reading. If you haven’t done this before, adding this code in the wrong place might bring the site down and the only way to access it is by editing functions.php file again via FTP. Feel free to contact us if you need help!
If you want to automatically apply all available coupons for customers who have referred friends, add the code below to function.php
add_action( 'woocommerce_before_calculate_totals', 'wpgens_auto_apply_coupons_checkout', 10, 1 );
function wpgens_auto_apply_coupons_checkout( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
if(!is_user_logged_in())
return;
$user_info = get_userdata(get_current_user_id());
$user_email = $user_info->user_email;
$date_format = get_option( 'date_format' );
$args = array(
'posts_per_page' => 10,
'post_type' => 'shop_coupon',
'post_status' => 'publish',
'meta_query' => array (
'relation' => 'AND',
array (
'key' => 'customer_email',
'value' => $user_email,
'compare' => 'LIKE'
),
array (
'key' => 'usage_count',
'value' => '0',
'compare' => '='
)
),
);
$raf_coupons = array();
$coupons = get_posts( $args );
if($coupons) {
$i = 0;
foreach ( $coupons as $coupon ) {
if(!$cart->has_discount( $coupon->post_title ) && substr( $coupon->post_title, 0, 3 ) === "RAF" ){
$cart->add_discount( $coupon->post_title );
}
}
}
}
This code will then automatically add coupons that the customer hasn’t used yet when they get to the checkout page. This is useful for users who have a large number of smaller coupons that they can combine.