我是计算购买的产品的折扣,根据其原价和折扣价格。数学运算成功了,我得到了正确的结果。
目前,当没有折扣0.00是显示,所以我想显示自定义文本,而不是值0,最终结果可能是“没有折扣应用”或类似的东西。
为了做到这一点,我考虑了是否和其他条件,但我不知道如何正确地应用它们,我是相对较新的。下面我留下我的代码解释一些事情,我希望有人帮助我和澄清这一点,我感谢任何答复,谢谢。
变量:我正在使用woocommerce,但我认为这是不相关的,因为php是关键的部分。无论如何,我有两个变量来恢复产品的原始价格和折扣价格:
$regular_price = $product->get_regular_price(); //Get original price
$total_discounted = $item->get_total(); //Get discounted price
计算:下面是考虑到这两个变量的计算折扣的php代码行。如果没有折扣,则显示值0,当应用折扣时,将显示正确的结果。请注意,我计算了折扣和百分比的总和。
<?php echo ' <span class="item-value summary">'. number_format( ($regular_price - $total_discounted),2 ) .'€ ('. number_format( (($regular_price - $total_discounted) / $regular_price*100),1 ) .'%)</span> '; ?>
下面,我留下了在这两个变量上执行var_dump所看到的内容。在现实中,xx是表示产品原价的数字,它从不为零。
<?php
var_dump($regular_price);
string(2) "xx" //Content - xx indicates the original price of the product
var_dump($total_discounted);
string(2) "xx" //Content - xx indicates the original price of the product
?>
我的疑问是,如果这两个变量都没有返回0,我该如何应用?计算结果显然返回0,但变量不返回。
发布于 2022-07-29 04:51:25
这是解决问题的办法。我创建了其他变量来定义如下的if条件:
$discount_sum = number_format( ($regular_price - $total_discounted),2 );
$discount_percentage = number_format( (($regular_price - $total_discounted) / $regular_price*100),1 );
if ($discount_sum == 0 and $discount_percentage == 0) {
echo '<span class="item-label summary t2-light">Nessuno sconto applicato</span>';
} else {
echo '<span class="item-value summary highlight">'. wp_kses_post($discount_sum) .'€ ('. wp_kses_post($discount_percentage) .'%)</span>';
}
https://stackoverflow.com/questions/73100856
复制