Search code examples
wordpresswoocommerceshopping-cartcoupondiscount

WooCommerce Student Discount


I need to create a coupon in WooCommerce that will only work if the user has an email which ends in .ac.uk.

For example [email protected] or [email protected].

The discount would be 10% off the total shopping basket.

I can't find any solutions online or any plugins which could help.

Any ideas?

Thanks.


Solution

  • You can use this Auto apply Discount Coupon to Customer’s Purchase function with the right conditionals (user email finishing by ac.uk):

    add_action('woocommerce_before_cart_table', 'coupon_auto_apply_user_email_tld', 10, 0);
    function coupon_auto_apply_user_email_tld() {
    
        $current_user = wp_get_current_user();
        $user_email = $current_user->user_email; 
        $mail_part = explode('@', $user_email);
        $domain_part = explode('.', $mailParts[1]);
        $mail_tld = $domain_part[1] . '.' . $domain_part[2];
    
        if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
    
        if ( $mail_tld == 'ac.uk' ) {
            $coupon_code = 'UNIQUECODE'; // <= set the name of your coupon code here
            if ( ! WC()->cart->add_discount( sanitize_text_field( $coupon_code ) ) ) {
                WC()->show_messages();
            }
            echo '<div class="woocommerce_message"><strong>The total price in your cart will be discounted 10% off…</strong></div>';
        }
        else
        {
            return;
        }
    }
    

    You will have to set in WooCommerce coupon settings a coupon with the desire behavior (10% off) and you will report this coupon slug in this function.

    Copy code in the functions.php file located in your active theme or better your active child theme.