Cancel sale for low stock products in WooCommerce

if ( ! function_exists( 'wpcb_is_product_low_stock' ) ) {
    /*
     * wpcb_is_product_low_stock.
     *
     * @see https://wpcodebook.com/snippets/cancel-sale-for-low-stock-products-in-woocommerce/
     */
    function wpcb_is_product_low_stock( $_product ) {
        return ( $_product->managing_stock() && $_product->get_stock_quantity() <= wc_get_low_stock_amount( $_product ) );
    }
}

if ( ! function_exists( 'wpcb_set_product_regular_price_on_low_stock' ) ) {
    /*
     * wpcb_set_product_regular_price_on_low_stock.
     */
    function wpcb_set_product_regular_price_on_low_stock( $price, $_product ) {
        return ( wpcb_is_product_low_stock( $_product ) ? $_product->get_regular_price() : $price );
    }
    add_filter( 'woocommerce_product_get_price', 'wpcb_set_product_regular_price_on_low_stock', PHP_INT_MAX, 2 );
}

if ( ! function_exists( 'wpcb_cancel_product_sale_on_low_stock' ) ) {
    /*
     * wpcb_cancel_product_sale_on_low_stock.
     */
    function wpcb_cancel_product_sale_on_low_stock( $is_on_sale, $_product ) {
        return ( wpcb_is_product_low_stock( $_product ) ? false : $is_on_sale );
    }
    add_filter( 'woocommerce_product_is_on_sale', 'wpcb_cancel_product_sale_on_low_stock', PHP_INT_MAX, 2 );
}

You can add this snippet to your (child) theme's functions.php file.

No comments yet.

Leave a Reply