Search code examples
wordpresssessionwoocommercesession-cookiescoupon

Add WooCommerce coupon through URL


I'm having troubles with applying coupons. The code below work except when the user visits the site for the first time and nothing has been added to the cart yet. I need to clear my cache in order to reproduce this error.

function process_url()
{
    if( empty($_GET['coupon']) )
        return;
    
    // Add the discount.
    WC()->cart->add_discount( wc_format_coupon_code(wp_unslash($_GET['coupon'])) )

}
add_action('init', 'process_url');

Am I doing something wrong?


Solution

  • Apparently the user session is not stored if you apply a coupon. You need to have first added a product or do something else which stores your session. We can do it manually though, namely by creating the session cookie ourselves.

    if( !WC()->session->has_session() )
        WC()->session->set_customer_session_cookie(true);
    

    Took me all day. Hopefully someone will be able use it.