DEV – Receives “out of stock” error when adding to cart even if it shouldn’t
-
A product is still “out of stock”, even thought it’s not marked as “Enable stock management at product level” and the product variations are not marked as “Manage stock?”. So it should be always in stock. But
add_to_cart()
fires “out of stock” anyway.What happens?
When I’m adding a product to cart I get the following error message:You cannot add "%s" to the cart because the product is out of stock.
Which also is weird that the product name is missing.
I add to cart via a WC hook
I have moved the “add to cart” function out to a custom function that I hook to Woocommerce with their*_add_variation_to_cart
hooks.I have checked so that the values of
$product_id
,$quantity
,$variation_id
and$variations
are correct./** * Add variation to cart */ function my_add_variation_to_cart() { global $woocommerce; ... A LOT OF CODE ... // Add to Cart if ($passed_validation && false !== WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variations) && 'publish' === $product_status) { do_action('woocommerce_ajax_added_to_cart', $product_id); } else { // If there was an error adding to the cart, redirect to the product page to show any errors. $data = array( 'error' => true, 'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id), ); wp_send_json($data); } die(); } add_action( 'wp_ajax_woocommerce_add_variation_to_cart', 'my_add_variation_to_cart' ); add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'my_add_variation_to_cart' );
Debugging
I have found that there is only one place in WooCommerce’s source code there the error message is fired. It’s in class-wc-cart.php in theadd_to_cart()
function.1. First I tried to copy that part that is checking stock and make my own function and placed it just above the
// Add to cart
section in my own code above:$product_data = wc_get_product( $variation_id ? $variation_id : $product_id ); if (!$product_data->is_in_stock()) { wc_add_notice( 'Product is out of stock', 'error' ); }
But that error message is not fired. So here it works. That’s very odd.
2. I then tried to simply remove the whole original part that fires the original error message in class-wc-cart.php. But this is probably most odd. The error message still fires when I try to add to cart. Even though that error message doesn’t exist anywhere in the code on the website. Or shouldn’t exist, I should probably say.
– I have deleted the WP Rocket cache
– And yes, the part is deleted even remotely and not just locallyWhat you may wanna have in mind (if that could affect this in any way) is that this is on a WP multisite installation.
What could cause this?
Why isis_in_stock()
returningfalse
? And why is it even returning anything at all when I have removed that part from the code?
- The topic ‘DEV – Receives “out of stock” error when adding to cart even if it shouldn’t’ is closed to new replies.