如果产品在 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;
}