phpwordpresswoocommercesession-cookiesurlvariables

WooCommerce Add to Cart Redirect with Session Cookie as URL variable


In WooCommerce, I am using woocommerce_add_to_cart_redirect filter hook on Add to Cart Redirect which works great. Now, I am trying to add WooCommerce session cookie as a URL parameter to use on the redirected platform.

Using the below method, I am able to redirect and GET the session cookie as a URL Parameter, but ONLY after navigating BACK to the main site and Adding to Cart AGAIN where the cookie is generated:

add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect', 10, 5 );
function custom_add_to_cart_redirect( $redirect_url) {
    $redirect_url = 'https://redirect.here.com';
    
    $wc_cookie = WC()->session->get_session_cookie();
    $wc_cookie = $wc_cookie[0];
    
    wp_safe_redirect( $redirect_url .'?paramname='.$wc_cookie); // Redirecting to the Quotation System
    exit;
}

This works fine however, I need to navigate back, add to cart again, and THEN, the redirect has the cookie value I need. I'm not sure if I need to use a different Woo filter or a method to WAIT for value THEN redirect?


Solution

  • First, there are some mistakes in your code, and it can be improved.

    As this filter hook is filtering the redirection URL, you don't need to make the redirection in the function.

    If you want the redirection to be auto triggered on add to cart, you need to go in:
    "Woocommerce" settings > "Product" tab > "General" subtab and on "Add to cart behaviour", you should enable "Redirect to the cart page after successful addition" and save.

    enter image description here

    The value that you need from the session cookie is the unique identifier, that can be obtained with get_customer_unique_id() method.

    Now to solve your question issue, You need to init the customer session (set the customer session cookie) as soon as possible, before add to cart.

    Here is the complete code:

    // Early enable woocommerce customer session
    add_action( 'woocommerce_init', 'early_enable_woocommerce_session_cookie' );
    function early_enable_woocommerce_session_cookie() {
        if( ! is_admin() && isset(WC()->session) && ! WC()->session->has_session() ) {
            WC()->session->set_customer_session_cookie( true ); 
        }
    }
    
    // Add to cart redirection to a custom URL with an URL variable
    add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect', 10, 5 );
    function custom_add_to_cart_redirect( $redirect_url ) {
        $redirect_url = 'https://redirect.here.com'; // Your redirection base url
    
        if ( isset(WC()->session) && WC()->session->has_session() ) {
            $redirect_url = add_query_arg( array( 'paramname' => WC()->session->get_customer_unique_id() ), $redirect_url );
        }
        return $redirect_url;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). It should work.