Home Forums Plugins CURCY – WooCommerce Multi Currency Auto Update isn’t working with custom hook, defaults exchange rate to 1.

Auto Update isn’t working with custom hook, defaults exchange rate to 1.

  • Author
    Posts
  • #187240

    I’ve created my plugin to retrieve data from NBP (Polish national bank).
    When I’m updating rates manually by using “Update All Rates” button everything is okay:

    However, when it auto-updates every 5 minutes or so, it defaults to 1.

    here is my plugin code:

    
    add_filter('wmc_get_currency_exchange_rates', 'custom_currency_exchange_rates', 10, 4);
    
    function custom_currency_exchange_rates($currency_data, $original_currency, $other_currency, $instance) {
        $custom_currency = get_currency_data($other_currency);
        $currency_data = [$other_currency => 1/$custom_currency['mid']];
        return $currency_data;
    }
    // Function to get currency data from NBP API
    function get_currency_data($currency_code) {
        $transient_key = 'currency_data_' . $currency_code;
        $api_url = 'http://api.nbp.pl/api/exchangerates/rates/a/' . strtolower($currency_code) . '/';
        $response = wp_remote_get($api_url);
    
        if (!is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
    
            if ($data && isset($data['rates'][0]['mid'])) {
                $currency_data = array(
                    'rate' => $data['rates'][0]['no'],
                    'mid' => $data['rates'][0]['mid'],
                    'effectiveDate' => $data['rates'][0]['effectiveDate']
                );
    
                // Update the last update time
                update_option('currency_data_last_update_time', current_time('timestamp'));
            }
        }   
        return $currency_data;
    }
    

    Am I missing something or did something wrong?

You must be logged in to see replies to this topic. Click here to login or register