Automatically apply coupons for users that come via a Referral link or referred friends
READ FIRST: This code needs to be added at the end of the functions.php file. If you are familiar with editing functions.php, 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 the 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 that have referred friends, follow the following steps:
- Log into your website
- Navigate to Appearance > Theme File Editor
- Select Theme Functions
- Add the code below at the end functions.php file
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 )){
$cart->add_discount( $coupon->post_title );
}
}
}
}
This code will then automatically add coupons that the user has not used yet once they get to the checkout page. This is useful for users that have a big number of smaller coupons that they can combine.