I’m using the following code to add text before the price if the product is on sale on the archive pages in WooCommerce:
function wps_custom_message() {
$product = wc_get_product();
if ( $product->is_on_sale() ) {
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
function cw_change_product_price_display( $price ) {
// Your additional text in a translatable string
$text = __('<span>Your sale price is:</span><br>');
// returning the text before the price
return $text . ' ' . $price;
}
}
}
add_action( 'woocommerce_archive_description', 'wps_custom_message', 9 );
add_action( 'woocommerce_before_single_product', 'wps_custom_message', 9 );
But the text appears also on products where sale price is not set.
What I’m doing wrong?
As you can see on the screenshot, the text shouldn’t be on the products that haven’t got sale price.
2
Answers
To prepend a text to products on sale price, replace your code simply with the following:
If you don’t want to have this on cart items, remove:
If you want to have this only on WooCommerce archive pages, replace:
with:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
You can use the
woocommerce_format_sale_price
filter. Have a look at the docs.