I'm trying to change the stock management
availability text on single product page based on different conditions in WooCommerce.
There are 5 situations, depending on whether 'Enable stock management at product level' is turned on
or off
.
- Turned on, Quantity: 0
- Turned on, Quantity: 2
- Turned on, Quantity: 3+
- Turned off, Out of stock
- Turned off, In stock
I'm using
add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
function wcs_custom_get_availability( $availability, $_product ) {
global $product;
// Case 3
if ( $_product->is_in_stock() ) {
$availability['availability'] = __('3. Turned on, Quantity: 3+', 'woocommerce');
}
// Case 2
if ( $_product->is_in_stock() && $product->get_stock_quantity() <= 2 ) {
$availability['availability'] = sprintf( __('2. Turned on, Quantity: 2', 'woocommerce');
}
// Case 5
if ( $_product->is_in_stock() && $product->get_stock_quantity() <= 0 ) {
$availability['availability'] = sprintf( __('5. Turned off, In stock', 'woocommerce'));
}
// Case 4 and 1 - out of stock
if ( ! $_product->is_in_stock() ) {
$availability['availability'] = __('4. Turned off, Out of stock / 1. Turned on, Quantity: 0', 'woocommerce');
}
return $availability;
}
But how to make it work for variable products?
For simple product it works perfect but for variable products 2 (out of 5) situations shows wrong results:
- Turned on, Quantity: 0 [Works ok]
- Turned on, Quantity: 2 [Wrong - shows case no.5]
- Turned on, Quantity: 3+ [Wrong - shows case no.5]
- Turned off, Out of stock [Works ok]
- Turned off, In stock [Works ok]