Created
March 4, 2012 11:40
-
-
Save rosshanney/1972608 to your computer and use it in GitHub Desktop.
Currency switcher thingy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin name: Currency switcher thingy | |
*/ | |
add_action( 'plugins_loaded', 'currency_setup' ); | |
function currency_setup() { | |
add_action( 'publish_post', 'currency_publish_post' ); | |
} | |
function currency_publish_post( $post_id ) { | |
//Get the price and currency custom fields | |
$price = get_post_meta( $post_id, 'price', true ); | |
$currency = get_post_meta( $post_id, 'currency', true ); | |
//If the custom fields aren't empty | |
if ( ! empty( $price ) && ! empty( $currency ) ) { | |
//Work out the prices in different currencies | |
$G = currency_exchange( $currency, 'GBP', $price ); | |
$E = currency_exchange( $currency, 'EUR', $price ); | |
$U = currency_exchange( $currency, 'USD', $price ); | |
//Add the exchanged prices to post meta, if the currency exchange was successful | |
//Using update_post_meta instead of add_post_meta, so values are updated on each save, rather than new values added | |
if ( false !== $G ) { | |
update_post_meta( $post_id, 'GBPprice', $G ); | |
} | |
if ( false !== $E ) { | |
update_post_meta( $post_id, 'EURprice', $E ); | |
} | |
if ( false !== $G ) { | |
update_post_meta( $post_id, 'USDprice', $U ); | |
} | |
} | |
} | |
function currency_exchange( $from, $to, $amount ) { | |
//Retrieve the currency exchange rates | |
$request = wp_remote_get( 'http://openexchangerates.org/latest.json' ); | |
//If the remote request didn't return an error | |
if ( ! is_wp_error( $request ) && 200 == $request['response']['code'] ) { | |
//Response is json format, so decode it into an array | |
$rates = json_decode( $request['body'], true ); | |
//If the json decoding was successful | |
if ( false !== $rates ) { | |
//Make sure the $from and $to parameter are strings | |
$from = (string) $from; | |
$to = (string) $to; | |
//Make sure the $amount parameter is a float | |
$amount = (float) $amount; | |
//If the $from and $to currencies exist in the array, work out the $amount in the $to currency and return it | |
if ( isset( $rates['rates'][$from] ) && isset( $rates['rates'][$to] ) ) { | |
return $amount * ( $rates['rates'][$to] * ( 1 / $rates['rates'][$from] ) ); | |
} else { | |
return false; //One or both of the specified currencies don't exist in the array | |
} | |
} else { | |
return false; //json_decode failed, perhaps invalid json | |
} | |
} else { | |
return false; //An error occurred when retrieving the data | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment