Check stock quantity of variants, instead of parent product
-
Hello, I have a e-commerce, based on Woocommerce. I have there simple products and variable products. All in one. My client ask me to add the “stock status” to the product archive. The page is using Hello Elementor & Elementor PRO.
I have added and edited the PHP snippet to my functions.php//* Add stock status to archive pages function envy_stock_catalog() { global $product; //var_dump($product->get_stock_quantity()); if ( $product->is_in_stock() && $product->get_stock_quantity() > 0 ) { echo '<div class="stock" >' . __( ' Skladom', 'envy' ) . '</div>'; } elseif($product->is_in_stock() && $product->get_stock_quantity() < 1) { echo '<div class="stock stock-order-only" >' . __( ' Na objednávku', 'envy' ) . '</div>'; } else { echo '<div class="out-of-stock" >' . __( 'Nie je na sklade', 'envy' ) . '</div>'; } } add_action( 'woocommerce_after_shop_loop_item_title', 'envy_stock_catalog' );
However there is a problem with variable products. It means, I have a product with variants. The stock quantiti is added to each variant, however the main product “stock” has no numbers. It means, even if some of variant is on stock, I am getting “Order only” status to product archive. I would need a function, which will check the stock status of variants, and if only one variant is on stock, in product archive I get “On stock” status.
For example, here’s my product: https://snipboard.io/lDTgHJ.jpg (Na objednávku means “Order only”)
Here’s how it is set in wp-admin: https://snipboard.io/cYArji.jpg main stock is turned off.However in variant there are some quantity: https://snipboard.io/fU1Kx9.jpg
I am getting still “Order only” in product archive. In my snippet there is something like
elseif($product->is_in_stock() && $product->get_stock_quantity() < 1)
So it seems, the$product->get_stock_quantity()
checks only parent products quantity, not the variant’s stock quantity. I need a function, which will check the variant’s stock quantity, instead of parent’s product quantity.Is possible to do something like this?
The page I need help with: [log in to see the link]
- The topic ‘Check stock quantity of variants, instead of parent product’ is closed to new replies.