我正在处理这段代码,虽然我已经尽力让它工作,但我无法修复分组产品的存档(商店页面(上发生的"除以零"错误。
这是错误消息: Warning: Division by zero in
这使得百分比文本如下所示:Save: -$18 (-INF%)
错误是指以下行:
$saving_percentage = round( 100 - ( $sale_price / $regular_price * 100 ), 1 ) . '%';
以下是完整代码:
add_filter( 'woocommerce_get_price_html', 'display_sale_price_and_percentage_html', 10, 2 );
function display_sale_price_and_percentage_html( $price, $product ) {
// sale products on frontend excluding variable products
if( $product->is_on_sale() && ! is_admin() && ! $product->is_type('variable')) {
// product prices
$regular_price = (float) $product->get_regular_price(); // Regular price
$sale_price = (float) $product->get_price();
// price calculation and formatting
$saving_price = wc_price( $regular_price - $sale_price );
// percentage calculation and formatting
$precision = 1; // decimals
$saving_percentage = round( 100 - ( $sale_price / $regular_price * 100 ), 1 ) . '%';
// display the formatted html price including amount and precentage using a span tag which means displaying it on the same row, if you want this on a new row, change the tag into a paragraph
$price .= sprintf( __('<span class="saved-sale"> Save: %s <em>(%s)</em></span>', 'woocommerce' ), $saving_price, $saving_percentage );
}
return $price;
}
错误显示在分组产品上。它在简单的产品上工作正常。我的目标是使它适用于所有产品类型(简单、分组、外部和可变(。
我需要我能得到的所有帮助。
我相信
这是因为分组产品没有$regular_price
。您应该添加一些条件来检查$sale_price
和$regular_price
是否不为零。您还可以检查您是否不在分组产品上,但检查 0 还可以防止在有免费产品的任何地方被零除错误。
add_filter( 'woocommerce_get_price_html', 'display_sale_price_and_percentage_html', 10, 2 );
function display_sale_price_and_percentage_html( $price, $product ) {
// sale products on frontend excluding variable products
if( $product->is_on_sale() && ! is_admin() && ! $product->is_type('variable')) {
// product prices
$regular_price = (float) $product->get_regular_price();
$sale_price = (float) $product->get_price();
if( $regular_price > 0 && $sale_price > 0 ) {
// price calculation and formatting
$saving_price = wc_price( $regular_price - $sale_price );
// percentage calculation and formatting
$precision = 1; // decimals
$saving_percentage = round( 100 - ( $sale_price / $regular_price * 100 ), 1 ) . '%';
// display the formatted html price including amount and precentage using a span tag which means displaying it on the same row, if you want this on a new row, change the tag into a paragraph
$price .= sprintf( __('<span class="saved-sale"> Save: %s <em>(%s)</em></span>', 'your-textdomain' ), $saving_price, $saving_percentage );
}
}
return $price;
}