obs
obs

Reputation: 807

Woocommerce: Add product to cart via ajax only works when logged in

I try to add products/variations to the woocommerce cart with ajax. When the button is clicked, I make a post request like this:

$data = {
   action: 'add_to_cart',
   productid: product_id,
   variationid: variation_id
};
$.post( $ajaxurl, $data, function(response) {
   // feedback to user
});

in the functions.php I have the following

add_action( 'wp_ajax_add_to_cart', 'add_to_cart' );
add_action( 'wp_ajax_nopriv_add_to_cart', 'add_to_cart' );
function add_to_cart(){

    global $woocommerce;

    $woocommerce->cart->maybe_set_cart_cookies(true);
    if( isset($_POST['variationid']) ){
        $woocommerce->cart->add_to_cart( $_POST['productid'], 1, $_POST['variationid'] );
    }
    else{
        $woocommerce->cart->add_to_cart( $_POST['productid'] );
    }

    echo $woocommerce->cart->get_cart_contents_count();

    wp_die();
}

This function returns the new amount of products in the cart, or when I echo the result of the add_to_cart I get the cart_item_key. So everything seems ok.

The thing I'm struggling with is, that it only works when I'm logged into WordPress, even though I get the same response of the add_to_cart function. When I visit the cart page while not logged in, I get an "empty cart" page.

Any ideas on this?

Additional info: as noted in the comments, when I'm logged in and have products in the cart and then log out, the cart is empty.

Upvotes: 0

Views: 2368

Answers (1)

obs
obs

Reputation: 807

I think I solved it!

the $woocommerce->cart->maybe_set_cart_cookies(true); has to come after $woocommerce->cart->add_to_cart( id );

Upvotes: 2

Related Questions