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. And I want to show current WooCommerce product price is divided by the fetched price. 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;
});
$bitprice = $json[0]["rate"];
instead of $bitprice = $json[0][rate];
, do not use implicit conversion by PHP, that is prone to error.Try this
$bitprice = intval($json[0][rate]);
echo $bitprice / $price;
intval
is a WordPress built-in function that converts string to int.
Edit:
Try this
$bitprice = intval($json[0]["rate"]);
echo $bitprice / $price;