Skip to content
Advertisement

Woocommerce Session cookie not set on ajax when using admin-ajax.php

I have a WordPress ajax function which is using the WC()->session to take session data and use it in the function. (for exmaple taking chosen shipping method from the session and displaying it).

The function is working properly on my local machine. However, it’s not working on WP Engine live server. I have already contacted them and they advised that the issue should not be on their side.

As far as I can see the following cookies are not being set on the live server only for admin-ajax.php request:

  • Set-Cookie: woocommerce_items_in_cart
  • Set-Cookie: woocommerce_cart_hash
  • Set-Cookie: wp_woocommerce_session

Does anyone have any idea what might cause this issue?

Advertisement

Answer

This is not normal and seems to be related to WP Engine hosting.

Now you should try to force enable Woocommerce Customer Session (if it’s not enabled yet), with the following code that will set the WC_Session cookie.

It could enable back WC()->session when using admin-ajax.php:

add_action( 'woocommerce_init', 'enable_wc_session_cookie' );
function enable_wc_session_cookie(){ 
    if( is_admin() )
       return;

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

Code goes in functions.php file of your active child theme (or active theme). It could works.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement