Click here to Skip to main content
15,877,591 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am experiencing an issue where the 'to' and 'from' attributes in my shortcode are working properly, but the 'amount' parameter is not. When attempting to change the value of the 'amount' parameter through the shortcode, the result is of always 1.

using the shortcode like this:
[exchange_rate from="USD" to="EUR" amount="100"]

What I have tried:

PHP
function currency_conversion_shortcode($atts) {
    $atts = shortcode_atts( array(
        'amount' => '1',
        'from' => 'USD',
        'to' => 'EUR',
    ), $atts, 'currency_conversion' );

    if (!is_numeric($atts['amount'])) {
        return "Invalid amount passed. Please pass a valid numeric value.";
    }

    $api_key = 'xxxxx-xxxx-xxxx';
    $url = "https://api.fastforex.io/convert?from=" . $atts['from'] . "&to=" . $atts['to'] . "&amount=" . $atts['amount'] . "&api_key=" . $api_key;

    $result = file_get_contents($url);
    if ($result === false) {
        return "Error: Failed to fetch data from API.";
    }

    $result = json_decode($result, true);
    if (!isset($result['result']['rate'])) {
        return "Error: Invalid response from API.";
    }

    return $atts['amount'] . " " . $atts['from'] . " = " . $result['result']['rate'] . " " . $atts['to'];
}

add_shortcode('currency_conversion', 'currency_conversion_shortcode');
Posted
Updated 19-Jan-23 22:53pm
Comments
Andre Oosthuizen 20-Jan-23 3:48am    
The problem might be lying with your API, check their documentation as it might have a solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900