【发布时间】:2017-04-13 09:16:57
【问题描述】:
我有这样的代码:
add_filter( 'woocommerce_sale_flash2', 'lx_custom_onsale_label', 10, 2 );
function lx_custom_onsale_label() {
global $product;
$percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 );
$absolute = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) ) );
if ($product->get_regular_price() > 100) {
return '<span class="onsalex bg_primary headerfont">'. sprintf( __(' -%s', 'salex' ), $absolute . ',-' ).'</span>';
}
else if ($product->get_regular_price() < 1) {
return '<span class="onsalessszzzx bg_primary headerfont">'. sprintf( __(' -%s', 'salex' ), $absolute . ',-' ).'</span>';
}
else {
return '<span class="onsalexzzz bg_primary headerfont">'. sprintf( __(' -%s', 'salex' ), $percentage . '%' ).'</span>';
}
}
一切正常,除了分隔符为 O 时,通知将显示:
警告:除以零 D:\SERVER\InstantWP_4.3.1\iwpserver\htdocs\wordpress\wp-content\themes\MYTHEME\functions.php 在第 553 行
第 553 行是这段代码:
$percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 );
我不明白如何避免该代码上条件为零的警告。
非常感谢您的帮助。
【问题讨论】:
-
厚脸皮的回答:不要除以零
-
在操作前测试
$product->get_regular_price()是否大于0 -
如果您不想做某事,
if非常方便