"Lowest Price in the Last 30 Days" for Sale Products
Records each product's price history and shows the lowest price of the 30 days before a sale under the sale price, as the EU Omnibus rules require.
Opens WPIDE on
Code
$wpide_omnibus_days = 30;
add_action( 'woocommerce_before_product_object_save', function ( $product ) {
$price = $product->get_price( 'edit' );
if ( '' === $price || null === $price ) {
return;
}
$history = (array) $product->get_meta( '_wpide_price_history' );
$today = wp_date( 'Y-m-d' );
$history = array_filter( $history, function ( $date ) {
return strtotime( $date ) > strtotime( '-60 days' );
}, ARRAY_FILTER_USE_KEY );
if ( ! isset( $history[ $today ] ) || (float) $price < (float) $history[ $today ] ) {
$history[ $today ] = (float) $price;
}
ksort( $history );
$product->update_meta_data( '_wpide_price_history', $history );
} );
add_filter( 'woocommerce_get_price_html', function ( $html, $product ) use ( $wpide_omnibus_days ) {
if ( ! $product->is_on_sale() || $product->is_type( 'variable' ) || ! is_product() ) {
return $html;
}
$history = (array) $product->get_meta( '_wpide_price_history' );
$from = $product->get_date_on_sale_from() ? $product->get_date_on_sale_from()->getTimestamp() : time();
$prices = array();
foreach ( $history as $date => $price ) {
$time = strtotime( $date );
if ( $time < $from && $time >= $from - $wpide_omnibus_days * DAY_IN_SECONDS ) {
$prices[] = (float) $price;
}
}
$prices[] = (float) $product->get_regular_price();
$lowest = min( array_filter( $prices ) );
return $html . sprintf( '<br><small class="wpide-omnibus">%s</small>', wp_kses_post( sprintf( 'Lowest price in the %1$d days before the sale: %2$s', $wpide_omnibus_days, wc_price( wc_get_price_to_display( $product, array( 'price' => $lowest ) ) ) ) ) );
}, 20, 2 );
Notes
Price history starts when you activate the snippet and is pruned after 60 days, so the note appears for sales that start after that.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.