If a product cannot be purchased because it is out of stock, why would you want to tell people that it’s on sale – only because it has a sale price?
That would probably clutter your shop and maybe get the customer to click on the wrong item just because it was standing out, only to find out they can’t purchase it!
So, let’s fix this little “design bug” in WooCommerce – let’s make sure the Sale! badge gets hidden in case the product is out of stock. Enjoy!
PHP Snippet: Remove “Sale!” If Current Product Is Out Of Stock @ WooCommerce Single Product & Shop Pages
Let me break down the code below:
add_filter()
function is used to edit specific data. In this case, we’re filtering thewoocommerce_sale_flash
output.- The callback function
bbloomer_no_sale_badge_if_out_of_stock
is hooked to thewoocommerce_sale_flash
hook. This function will be called when thewoocommerce_sale_flash
hook is triggered. - The function
bbloomer_no_sale_badge_if_out_of_stock
takes three parameters:$html
,$post
, and$product
. - Inside the function, it first checks if the product is not in stock using
$product->is_in_stock()
function. If the product is not in stock, it returns early, hence it does not output any HTML. - If the product is in stock, it returns the original
$html
. This essentially means that if the product is in stock, the sale flash HTML remains unchanged.
In summary, this PHP code ensures that the sale flash badge is only displayed for products that are in stock. If a product is out of stock, the sale flash badge won’t be displayed.
/**
* @snippet No Sale Badge If Out Of Stock @ WooCommerce Product, Shop
* @tutorial Get CustomizeWoo.com FREE
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 8
* @community Join https://businessbloomer.com/club/
*/
add_filter( 'woocommerce_sale_flash', 'bbloomer_no_sale_badge_if_out_of_stock', 9999, 3 );
function bbloomer_no_sale_badge_if_out_of_stock( $html, $post, $product ) {
if ( ! $product->is_in_stock() ) return;
return $html;
}
Great explanation, very clear and easy to understand !
Thank you!