我一直在测试代码,因为您的目标是可变产品的销售价格范围,所以最好在中使用自定义挂钩函数
woocommerce_format_sale_price
位于
wc_format_sale_price()
作用
这将允许在所有变体具有相同价格时,在价格范围后显示保存的折扣百分比。如果变更价格不同,则该百分比将仅出现在变更价格上。
因此,我重新访问了您的代码:
// Removing sale badge
add_filter('woocommerce_sale_flash', '__return_false');
// Removing archives prices
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
// Add the saved discounted percentage to variable products
add_filter('woocommerce_format_sale_price', 'add_sale_price_percentage', 20, 3 );
function add_sale_price_percentage( $price, $regular_price, $sale_price ){
// Strip html tags and currency (we keep only the float number)
$regular_price = strip_tags( $regular_price );
$regular_price = (float) preg_replace('/[^0-9.]+/', '', $regular_price);
$sale_price = strip_tags( $sale_price );
$sale_price = (float) preg_replace('/[^0-9.]+/', '', $sale_price);
// Percentage text and calculation
$percentage = __('Save', 'woocommerce') . ' ';
$percentage .= round( ( $regular_price - $sale_price ) / $regular_price * 100 );
// return on sale price range with "Save " and the discounted percentage
return $price . ' <span class="save-percent">' . $percentage . '%</span>';
}
代码进入功能。活动子主题(活动主题)的php文件。
已测试并正常工作。