I have a custom template file, rendering some products and their Add To Cart buttons, that I am trying to implement manually. When Add to Cart is pressed, the page is reloaded and a $_POST variable containing some data adds the new products. 'cart_contents_count' also reflects the added item. However, when I go to the cart page, it's empty. Please see the following code.
global $woocommerce;
if ( isset( $_POST['AddedToCart'] ) ) {
$woocommerce->cart->add_to_cart($_POST['event'], $_POST['qty']);
}
$cart_total = $woocommerce->cart->cart_contents_count;
When I however go to the normal default shop page ( /shop/ ) and add a product from there, my cart page indicates that this product has been added. When I NOW go to my custom page and add products from that Add To Cart button, it works perfectly.
It seems to me that, before I run the above-mentioned code, I must check if a Cart Session has been initialized, and if not, initialize it. Could someone please confirm for me that I understand it right and show me how to initialize the cart?
I resolved this problem by making sure the
$woocommerce->cart->add_to_cart()
line is positioned before any headers are sent. I.E, beforeget_header()
is called on my custom template.Here is a solution if your custom form is on a page template. This code goes in your functions.php file. Be sure to change
yourtheme_template
to something more unique. Also, change the items in the$session_templates
array to the template filenames where you want this filter to be used. It uses thetemplate_include
filter, which isn't an easy filter to track down, let alone$woocommerce->session->set_customer_session_cookie(true)
- Special thanks to @vrazer (on twitter) for the help.In the WooCommerce version 2.5 they change the way the sessions works. https://woocommerce.wordpress.com/2015/10/07/new-session-handler-in-2-5/ What i did was install this plugin https://github.com/kloon/woocommerce-large-sessions then my cart is not empty any more with guess users.
I hope it helps someone else.