How to properly initialize a Woocommerce basket

I have a custom template file, rendering of some products and their Add to Cart buttons, which I try to implement manually. When you click the Add to Cart button, the page reloads, and the $ _POST variable, containing some data, adds new products. 'cart_contents_count' also reflects the added item. However, when I go to the cart page, it is empty. 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 regular default store page (/ shop /) and add the product from there, my shopping cart page indicates that this product has been added. When I NOW go to my own page and add products from this "Add to Cart" button, it works great.

It seems to me that before running the above code, I should check if the Cart session is initialized, and if not, initialize it. Can someone please confirm that I understand correctly and show how to initialize the basket?

+4
source share
3 answers

, . functions.php. yourtheme_template . , $session_templates , , . template_include, , $woocommerce->session->set_customer_session_cookie(true). @vrazer ( ) .

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');
+10

, , $woocommerce->cart->add_to_cart() . I.E, get_header() .

0

In version 2.5 of WooCommerce, they change the way sessions work. 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 , after which my cart is no longer empty with guessing users.

I hope this helps someone else.

0
source

Source: https://habr.com/ru/post/1546483/


All Articles