I have a problem when I try to retrieve the available quantity of a product in my view.
This is my code :
function wcs_custom_get_availability( $availability, $_product ) {
global $product;
// Change In Stock Text
if ( $_product->is_in_stock() ) {
$availability['availability'] = __( 'Plenty available in our store!', 'woocommerce');
}
// Change in Stock Text to only 1 or 2 left
if ( $_product->is_in_stock() && $product->get_stock_quantity() <= 2 ) {
$availability['availability'] = sprintf( __('Only %s left in store!', 'woocommerce'), $product->get_stock_quantity() );
}
// Change Out of Stock Text
if ( ! $_product->is_in_stock() ) {
$availability['availability'] = __('Sorry, All sold out!', 'woocommerce');
}
return $availability;
}
The result of the execution is as follows : Only left in store!
I have access to the product variable but the result is null but I would like to retrieve the quantity.
3
Answers
Correction :
Replace
$product->get_stock_quantity()
by$_product->get_stock_quantity()
.Using
WC_Product
methodget_manage_stock()
with it, you will be able to avoid this problem. I have also simplified a bit your code:It should solve this problem.
in my case none of the answers worked, so I figured it out by myself. The thing is you should check first if
managing_stock()
is on. If it is, then we’re good to go.So, the final code is: