#StackBounty: #php #wordpress #woocommerce Woo Commerce Custom Quick Shop script add items to cart sometimes failing to add

Bounty: 50

I have a Woo Commerce store that has a custom "quick shop" page. This page outputs all products from a particular category. It allows a user to increase the quantity next to any items they wish to buy. They then click the "Add selected items to cart" button. This takes the form data, matches it against shop products, tidies it all up, and then iterates over them to add each to the cart. Finally, it redirects users to the cart page.

What is happening is that, sometimes, we use the quick shop and when we get redirected, some items are missing. We do however ALWAYS get a message stating that the item has been added.

We have noticed though, that if the basket is empty before using the quick shop then it sometimes works ok but other times it shows empty until we refresh and then the items appear.

If the basket already has some items in then some items go missing and a refresh doesn’t help.

After the processing of the raw $_POST data, we end up with an array something like the following:

Array ( [0] => Array ( [category_id] => 1075 [product_id] => 27020 [quantity] => 1 [attributes] => Array ( [colour] => Navy [size] => Large ) [variation_id] => 38172 ) [1] => Array ( [category_id] => 1075 [product_id] => 27550 [quantity] => 1 ) )

We then iterate over this as below:

// Add products to the cart
foreach ($products_to_add as $product) {
    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product['product_id'], $product['quantity']);

    if (isset($product['variation_id'])) {
        if ($passed_validation && false !== WC()->cart->add_to_cart($product['product_id'], $product['quantity'], $product['variation_id'], wc_get_product_variation_attributes($product['variation_id']))) {
            wc_add_to_cart_message($product['product_id']);
        }
    } else {
        if ($passed_validation && false !== WC()->cart->add_to_cart($product['product_id'], $product['quantity'])) {
            wc_add_to_cart_message($product['product_id']);
        }         
    }
}

After this loop we have a few extra bits and then the redirect:

// Calculate totals
WC()->cart->calculate_totals();

// Save cart to session
WC()->cart->set_session();     

// Set cookies if needed
WC()->cart->maybe_set_cart_cookies();

wp_safe_redirect( wc_get_cart_url() );
exit();

I really don’t think it’s a product issue. I think it could possibly be an issue with the few lines I posted just above but I’m not 100% sure on what I should be running after adding all the items to the cart programmatically in the loop beforehand.

Anyone with a good in-depth knowledge of WooCommerce able to help us out?

Thanks.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.