I would like to limit the display of stocks on my product pages (only on the frontend) in order to limit the stocks that are too high.
My question is similar to this article:
The returned value should replace the stock displayed on the product pages taking into account these conditions:
- When a stock is greater than 50, display a random number between 50 and 100.
- If the stock is less than 50, display the real value of the stock.
I am stuck and I don't know if I am going in the right direction, Thanks a lot in advance!
CodePudding user response:
You could filter the woocommerce_get_availability_text
and check the stock quantity.
add_filter( 'woocommerce_get_availability_text', 'custom_availability_text', 10, 2 );
function custom_availability_text( $availability, $product ) {
if ( ! $product->is_in_stock() ) {
$availability = __( 'Out of stock', 'woocommerce' );
} elseif ( $product->managing_stock() && $product->is_on_backorder( 1 ) ) {
$availability = $product->backorders_require_notification() ? __( 'Available on backorder', 'woocommerce' ) : '';
} elseif ( ! $product->managing_stock() && $product->is_on_backorder( 1 ) ) {
$availability = __( 'Available on backorder', 'woocommerce' );
} elseif ( $product->managing_stock() ) {
$stock_amount = $product->get_stock_quantity();
// Check if Stock is less than 50.
if ( 50 > $stock_amount ) {
$availability = wc_format_stock_for_display( $product );
} else {
if ( false === ( $custom_availability = get_transient( 'custom_availability_text_' . $product->get_id() ) ) ) {
$random = wp_rand( 50, 100 );
$availability = sprintf( __( '%s in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $random, $product ) );
// Store for 6 hours. YMMV.
set_transient( 'custom_availability_text_' . $product->get_id(), $availability, 6 * HOUR_IN_SECONDS );
} else {
return $custom_availability;
}
}
} else {
$availability = '';
}
return $availability;
}
I've updated the answer to include a 6 hour cache.