Problem adding Product to Woocommerce Basket in my Code


(Jonathan Buckland) #1

Hi

I’m an experience .NET developer that’s moving across to Wordpress development, so excuse if I haven’t quite grasped the correct approaches to develop on this platform.

I’m currently developing a bespoke wristband design page for a client and I’ve coded up the page. When the form Add to Basket it clicked I check to see if $_POST[“status”] is set and then I do the following:

global $woocommerce;
$productId = intval($_POST[“spd-design-color”]);
$added = $woocommerce->cart->add_to_cart( $productId, $quantity=1 );

When I check the basket it’s not there and $add is returning null.

Strangely when I look in the debug log it shows the following error:

woocommerce_cart_hash cookie cannot be set

Any ideas where I might be going wrong?


(Leland Fiegel) #2

I’m not a WooCommerce expert by any means, but is there a reason you’re not just using WooCommerce’s natural add-to-cart flow? It shouldn’t require any custom code.

Also, it looks like you’re getting the PHP $_POST variable variable confused with the WordPress $post variable.

Try looking at the get_the_id function instead to better pass a post ID to the $productId.

But anyway, back to my first point…you shouldn’t need to write any custom code to allow customers to add products to the cart. Unless you’re trying to do something else?