WordPress: Convert between currencies

July 20, 2012

If you have ever built a project dealing with money and multiple countries you have probably encountered the need to convert between currencies. There are a lot of examples on how to convert currencies using the Google currency calculator in PHP, however they almost all use CURL to accomplish the task. WordPress has an HTTP API that we can tap into that will retrieve data from anywhere in one line of code. If you are building a plugin for WordPress that makes any sort of external calls I highly recommend using this approach. If you need to convert currencies with the Google currency calculator the following snip of code will come in handy.


function convertCurrency( $Amount, $Original, $New ) {
        $url = "http://www.google.com/ig/calculator?hl=en&q=$Amount$Original=?$New";
        $res = ( wp_remote_retrieve_body( wp_remote_get($url) ) );
        $data = explode('"', $res);
        $data = explode(' ', $data['3']);
        $var = $data['0'];
        $res = round($var,3);
        return $res;
Leave a Reply

Your email address will not be published. Required fields are marked *