以下代码将根据产品是否在销售以及页面类型(single product, shop, archives, cart and checkout)的不同,向显示的价格添加不同的字符串前缀:
add_filter( 'woocommerce_get_price_html', 'add_string_prefix_to_price_html', 10, 2 );
function add_string_prefix_to_price_html( $price_html, $product ) {
global $woocommerce_loop;
// Not on related products
if ( isset($woocommerce_loop['name']) && $woocommerce_loop['name'] === 'related' ) {
return $price_html;
}
$prefix = ''; // Initializing
// Set the text by section type
if ( is_shop() ) {
if ( $product->is_on_sale() ){
$prefix = __('ON SALE SHOP', 'woocommerce') . ' ';
} else {
$prefix = __('NORMAL SHOP', 'woocommerce') . ' '; // optional
}
} elseif( is_tax() ) {
if ( $product->is_on_sale() ){
$prefix = __('ON SALE ARCHIVES', 'woocommerce') . ' ';
} else {
$prefix = __('NORMAL ARCHIVES', 'woocommerce') . ' '; // optional
}
} elseif( is_product() ) {
if ( $product->is_on_sale() ){
$prefix = __('ON SALE PRODUCT', 'woocommerce') . ' ';
} else {
$prefix = __('NORMAL PRODUCT', 'woocommerce') . ' '; // optional
}
} else {
if ( $product->is_on_sale() ){
$prefix = __('ON SALE OTHERS', 'woocommerce') . ' ';
} else {
$prefix = __('NORMAL OTHERS', 'woocommerce') . ' '; // optional
}
}
return $prefix . $price_html;
}
// For cart (optional)
add_filter( 'woocommerce_cart_item_price', 'add_string_prefix_to_cart_item_price_html', 10, 2 );
function add_string_prefix_to_cart_item_price_html( $price_html, $cart_item ) {
$prefix = ''; // Initializing
if ( $cart_item['data']->is_on_sale() ){
$prefix = __('ON SALE CART', 'woocommerce') . ' ';
} else {
$prefix = __('NORMAL CART', 'woocommerce') . ' '; // optional
}
return $prefix . $price_html;
}
// For checkout (optional)
add_filter( 'woocommerce_cart_item_subtotal', 'add_string_prefix_to_checkout_item_subtotal_html', 10, 2 );
function add_string_prefix_to_checkout_item_subtotal_html( $subtotal_html, $cart_item ) {
$prefix = ''; // Initializing
if( is_checkout() ) {
if ( $cart_item['data']->is_on_sale() ){
$prefix = __('ON SALE CHECKOUT', 'woocommerce') . ' ';
} else {
$prefix = __('NORMAL CHECKOUT', 'woocommerce') . ' '; // optional
}
}
return $prefix . $subtotal_html;
}
代码位于您的子主题的unctions.php文件中(或在插件中).经过测试,效果良好.