简体   繁体   English

警告:在 WooCommerce 上除以零

[英]Warning: Division by zero on WooCommerce

I am creating a WordPress plugin and what it does is actually fetch a JSON API via a URL and it shows price using Loop.我正在创建一个 WordPress 插件,它实际上是通过 URL 获取 JSON API,并使用 Loop 显示价格。 And I want to show current WooCommerce product price is divided by the fetched price.我想显示当前 WooCommerce 产品价格除以获取的价格。 But, it all time shows me a error: Warning: Division by Zero.但是,它一直向我显示一个错误:警告:除以零。 I am writing the code here.我在这里写代码。 Could anyone please tell me what did I have done wrong?谁能告诉我我做错了什么?

add_filter('woocommerce_get_price_html', function($price) {

$url = 'https://bitpay.com/api/rates';
$details = file_get_contents($url);
$json = json_decode($details, true);

$bitprice = $json[0][rate];
echo $bitprice / $price;    

});
  1. It should be $bitprice = $json[0]["rate"];它应该是$bitprice = $json[0]["rate"]; instead of $bitprice = $json[0][rate];而不是$bitprice = $json[0][rate]; , do not use implicit conversion by PHP, that is prone to error. , 不要使用 PHP 的隐式转换,那样容易出错。
  2. Your price value is a string, which is not getting converted to an integer properly, hence being typecasted as 0.您的价格值是一个字符串,它没有正确转换为整数,因此被类型转换为 0。

Try this尝试这个

$bitprice = intval($json[0][rate]);
echo $bitprice / $price;   

intval is a WordPress built-in function that converts string to int. intval是一个 WordPress 内置函数,可将字符串转换为 int。

Edit :编辑

Try this尝试这个

$bitprice = intval($json[0]["rate"]);
echo $bitprice / $price;   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM