我正在尝试在Woocommerce上显示产品的折扣百分比。最初提供的解决方案(在下面链接)有效,但是,如果存在默认的产品差异集,则不会显示折扣百分比。仅当选择更改为另一个变体时,百分比折扣才会出现。我将如何修改代码以立即显示折扣百分比,而无需选择其他变体?
源代码: Display the discounted price and percentage on Woocommerce products (选项2)
2)节省百分比:
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('variable')){
// 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 ), 1 ) . '%';
// Append to the formated html price
$price .= sprintf( __('<p class="saved-sale">Save: %s</p>', 'woocommerce' ), $saving_percentage );
}
return $price;
}
答案 0 :(得分:1)
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( __('<p class="saved-sale">Save: %s</p>', 'woocommerce' ), $saving_percentage );
}
return $data;
}
代码进入活动子主题(或活动主题)的functions.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( __('<p class="saved-sale">Save: %s</p>', 'woocommerce' ), $saving_percentage );
}
return $price;
}
代码进入活动子主题(或活动主题)的functions.php文件中。