【发布时间】:2018-04-13 09:34:49
【问题描述】:
我正在使用 wordpress / woocommerce 并获得这样的产品价格:
$get_price = get_post_meta( $item_id, '_regular_price', true);
然后我正在计算折扣并像这样删除它:
$discount = 10;
$minus = ($discount / 100) * $get_price;
$price = wc_price($get_price - $minus);
由于某种原因,我收到以下错误:
CRITICAL Uncaught Error: Unsupported operand types in .....
指向以 $minus = ... 开头的行
我使用“gettype”进行了一些挖掘,发现 woocommerce 价格存储为字符串,而不是整数。
然后我将上面的内容更改为这个以确保它现在是一个整数:
$discount = 10;
$minus = ($discount / 100) * (int)$get_price;
$price = wc_price($get_price - $minus);
现在可以使用了,但它会将产品的价格从 13.97 英镑降低到 13.00 英镑。任何想法为什么会这样?以及为什么价格首先存储为字符串的任何原因?
编辑
我现在尝试了以下方法:
$get_price = get_post_meta( $item_id, '_regular_price', true);
$new_price = (float) $get_price;
echo gettype($new_price);
仍然返回字符串。
【问题讨论】:
-
尝试使用
(float)而不是(int),但请注意,在货币计算中使用浮点运算是一种不好的做法——通过将值乘以(10^(needed precision + 1))将它们转换为整数,反转该计算为最终结果。 -
您将价格转换为 int,因此它变为 13:3v4l.org/54O3T - 将价格作为浮点值处理是一种不好的做法,因为您会在任何地方遇到计算问题。
-
@LoicTheAztec 尝试了这个并且仍然作为字符串返回?
-
@danyo php-7.2 psysh 会话:
>>> gettype((float)'13.97'); => "double -
@LoicTheAztec 这无关紧要,$item_id = get_the_id();这是当前产品的 id。
标签: php wordpress string woocommerce integer