这个
linked code works
此外,当可变产品有默认的所选变体(在售)并正确显示折扣百分比时,
现在,对于可变产品的一般显示价格范围,
不能显示折扣百分比
,因为所有的变化都需要出售,每个变化的折扣百分比可能不同。
供选择
销售产品变化
价格,您还可以使用以下方法获得节省百分比:
// For product variations
add_filter( 'woocommerce_available_variation', 'custom_variation_price_saving_percentage', 10, 3 );
function custom_variation_price_saving_percentage( $data, $product, $variation ) {
$active_price = $data['display_price'];
$regular_price = $data['display_regular_price'];
if( $active_price !== $regular_price ) {
$saving_percentage = round( 100 - ( $active_price / $regular_price * 100 ), 1 ) . '%';
$data['price_html'] .= sprintf( __('
Save: %s
', 'woocommerce' ), $saving_percentage );}
return $data;
}
代码位于活动子主题(或活动主题)的function.php文件中。
对于简单产品,您将使用:
// For simple products
add_filter( 'woocommerce_get_price_html', 'change_displayed_sale_price_html', 10, 2 );
function change_displayed_sale_price_html( $price, $product ) {
// Only on sale products on frontend and excluding min/max price on variable products
if( $product->is_on_sale() && ! is_admin() && $product->is_type('simple') ){
// Get product prices
$regular_price = (float) $product->get_regular_price(); // Regular price
$sale_price = (float) $product->get_price(); // Active price (the "Sale price" when on-sale)
// "Saving Percentage" calculation and formatting
$precision = 1; // Max number of decimals
$saving_percentage = round( 100 - ( $sale_price / $regular_price * 100 ), $precision ) . '%';
// Append to the formated html price
$price .= sprintf( __('
Save: %s
', 'woocommerce' ), $saving_percentage );}
return $price;
}
代码位于活动子主题(或活动主题)的function.php文件中。