请您参考如下方法:
您应该能够连接到 woocommerce_sale_flash
过滤,获取产品对象,计算出百分比并将其添加到 HTML 中。
像这样的东西:
add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_bubble' );
function add_percentage_to_sale_bubble( $html ) {
global $product;
$percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
$output =' <span class="onsale">VERKOOP -'.$percentage.'%</span>';
return $output;
}
编辑 - 可变产品:
随着可变产品混入其中,您需要使用
is_type('simple|variable')
进行检查。并从那里调整您的计算,如下所示:
add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_bubble', 20 );
function add_percentage_to_sale_bubble( $html ) {
global $product;
if ($product->is_type('simple')) { //if simple product
$percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 ).'%';
} else { //if variable product
$percentage = get_variable_sale_percentage( $product );
}
$output =' <span class="onsale">-'.$percentage.'</span>';
return $output;
}
function get_variable_sale_percentage( $product ) {
//get variables
$variation_min_regular_price = $product->get_variation_regular_price('min', true);
$variation_max_regular_price = $product->get_variation_regular_price('max', true);
$variation_min_sale_price = $product->get_variation_sale_price('min', true);
$variation_max_sale_price = $product->get_variation_sale_price('max', true);
//get highest and lowest percentages
$lower_percentage = round( ( ( $variation_min_regular_price - $variation_min_sale_price ) / $variation_min_regular_price ) * 100 );
$higher_percentage = round( ( ( $variation_max_regular_price - $variation_max_sale_price ) / $variation_max_regular_price ) * 100 );
//sort array
$percentages = array($lower_percentage, $higher_percentage);
sort($percentages);
if ($percentages[0] != $percentages[1] && $percentages[0]) {
return $percentages[0].'% - '.$percentages[1].'%';
} else {
return $percentages[1].'%';
}
}