Automatically apply coupons for users that have 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, feel free to continue reading. If you haven't done this before, adding this code in 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 users that have referred friends, add below code 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 user has not used yet once he hits the checkout page. Useful for users that have big number of smaller coupons that they can combine. 

Still need help? Contact Us Contact Us