如果产品在 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 );
但该文字也会出现在未设定销售价格的产品上。
我做错了什么?
正如您在屏幕截图中看到的,文本不应该出现在没有促销价的产品上。
要将文本添加到促销价格的产品中,只需将您的代码替换为以下内容:
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display', 100, 2 );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display', 100, 2 );
function cw_change_product_price_display( $price_html, $mixed ) {
$product = is_a($mixed, 'WC_product') ? $mixed : $mixed['data'];
if ( $product->is_on_sale() ) {
$price_html = sprintf('<span>%s:</span> <br>%s', __('Your sale price is', 'woocommerce'), $price_html);
}
return $price_html;
}
如果您不想在购物车商品上添加此内容,请删除:
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display', 100, 2 );
如果您只想在 WooCommerce 存档页面上使用此内容,请替换:
if ( $product->is_on_sale() ) {
与:
if ( ! is_product() && $product->is_on_sale() ) {
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。
您可以使用
woocommerce_format_sale_price
过滤器。看一下文档。
add_filter( 'woocommerce_format_sale_price', 'add_text_to_sales', 100, 3 );
function add_text_to_sales( $price, $regular_price, $sale_price ) {
// Your additional text in a translatable string
$text = __('<span>Your sale price is:</span><br>');
return $text . $price;
}