Skip to content

Instantly share code, notes, and snippets.

@ricardobrg
Last active November 3, 2016 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardobrg/b5ed041cb69ecc6b71091409c12ab536 to your computer and use it in GitHub Desktop.
Save ricardobrg/b5ed041cb69ecc6b71091409c12ab536 to your computer and use it in GitHub Desktop.
Atualiza a cotação do dólar com YQL e salva no wp_options
//cria o wp_cron para checar a cotação a cada hora
add_action('wp','brg_agenda_cotacao');
function brg_agenda_cotacao() {
if (! wp_next_scheduled ( 'brg_atualiza_cotacao' )) {
wp_schedule_event(time(), 'hourly', 'brg_atualiza_cotacao');
}
}
//função para atualizar a cotação no wp_options
add_action('brg_atualiza_cotacao', 'brg_cotacao_dolar');
function brg_cotacao_dolar(){
$url = "https://query.yahooapis.com/v1/public/yql?q=env%20'store%3A%2F%2Fdatatables.org%2Falltableswithkeys'%3B%20select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDBRL%22)&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$xml_feed_url = $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $xml_feed_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($ch);
curl_close($ch);
libxml_use_internal_errors(true);
try {
$xmlTree = new SimpleXMLElement($xml);
} catch (Exception $e) {
// Something went wrong.
$error_message = 'SimpleXMLElement threw an exception.';
foreach(libxml_get_errors() as $error_line) {
$error_message .= "\t" . $error_line->message;
}
trigger_error($error_message);
$xmlTree = false;
}
if ($xmlTree){
$usd = $xmlTree->results->rate[0]->Rate;
$usd = (float)$usd;
if ($usd>0){
update_option ('cotacao_dolar',$usd);
update_option ('cotacao_atualizada',date('d/m/Y H:i:s'));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment