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?


Solution:

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 the template_include filter, which isn't an easy filter to track down, let alone $woocommerce->session->set_customer_session_cookie(true)

function yourtheme_template($template) {
//List of template file names that require WooCommerce session creation
$session_templates = array(
    'page-template-file-name.php', 'another-page-template-filename.php'
);
//Split up the template path into parts so the template file name can be retrieved
$parts = explode('/', $template);
//Check the template file name against the session_templates list and instantiate the session if the
//template is in the list and the user is not already logged in.  If the session already exists from
//having created a cart, WooCommerce will not destroy the active session
 if (in_array($parts[count($parts) - 1], $session_templates)  && !is_user_logged_in()) {
 global $woocommerce;
  $woocommerce->session->set_customer_session_cookie(true);
 }
 return $template;
}
//Filter to run the WooCommerce conditional session instantiation code
add_filter('template_include', 'yourtheme_template');

Related Wordpress search:

, , ,

Wordpress related questions and answers: