Developer’s Notes: How to implement Coupon URL in WooCommerce

Stack Overflow is the developer’s best friend.

Our friends there have published a very useful code for implementing Coupon URL without the need for a paid plugin.

By adding the below code in the function.php file of your template you can use the URL in the below format, and have the coupon automatically applied when visiting the link.

https://example.com/?coupon_code=mycouponcode

It is a cool feature since you can share coupon links with your potential customers.

CODE:

add_action('init', 'get_custom_coupon_code_to_session');
function get_custom_coupon_code_to_session(){
    if( isset($_GET['coupon_code']) ){
        // Ensure that customer session is started
        if( isset(WC()->session) && ! WC()->session->has_session() )
            WC()->session->set_customer_session_cookie(true);
            
        // Check and register coupon code in a custom session variable
        $coupon_code = WC()->session->get('coupon_code');
        if(empty($coupon_code)){
            $coupon_code = esc_attr( $_GET['coupon_code'] );
            WC()->session->set( 'coupon_code', $coupon_code ); // Set the coupon code in session
        }
    }
}

add_action( 'woocommerce_before_checkout_form', 'add_discout_to_checkout', 10, 0 );
function add_discout_to_checkout( ) {
    // Set coupon code
    $coupon_code = WC()->session->get('coupon_code');
    if ( ! empty( $coupon_code ) && ! WC()->cart->has_discount( $coupon_code ) ){
        WC()->cart->add_discount( $coupon_code ); // apply the coupon discount
        WC()->session->__unset('coupon_code'); // remove coupon code from session
    }
}

Share your thoughts