Exemplos
WordPress
Integre cotações da B3 no WordPress usando shortcodes personalizados.
Implementação
Adicione este código ao arquivo functions.php
do seu tema ou em um plugin personalizado:
<?php
function brapi_get_stock_price($ticker) {
$token = get_option('brapi_token', 'SEU_TOKEN');
// Cache de 60 segundos
$transient_key = 'brapi_quote_' . $ticker;
$cached = get_transient($transient_key);
if ($cached !== false) {
return $cached;
}
$url = "https://brapi.dev/api/quote/{$ticker}?token={$token}";
$response = wp_remote_get($url, ['timeout' => 10]);
if (is_wp_error($response)) {
return 'Erro ao buscar dados';
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['results'][0]['regularMarketPrice'])) {
$price = $data['results'][0]['regularMarketPrice'];
set_transient($transient_key, $price, 60);
return $price;
}
return 'Cotação indisponível';
}
function brapi_stock_price_shortcode($atts) {
$atts = shortcode_atts([
'ticker' => 'PETR4',
], $atts);
$price = brapi_get_stock_price($atts['ticker']);
if (is_numeric($price)) {
return 'R$ ' . number_format($price, 2, ',', '.');
}
return $price;
}
add_shortcode('brapi_cotacao', 'brapi_stock_price_shortcode');
?>
Uso no WordPress
Use o shortcode em posts e páginas:
[brapi_cotacao ticker="PETR4"]
Exemplos:
[brapi_cotacao ticker="VALE3"]
[brapi_cotacao ticker="ITUB4"]
[brapi_cotacao ticker="IMAB11"]
Com Widget Gutenberg
Para criar um bloco customizado:
<?php
function brapi_register_block() {
wp_register_script(
'brapi-block',
get_template_directory_uri() . '/blocks/brapi-block.js',
['wp-blocks', 'wp-element', 'wp-editor']
);
register_block_type('brapi/stock-quote', [
'editor_script' => 'brapi-block',
'render_callback' => 'brapi_render_block'
]);
}
add_action('init', 'brapi_register_block');
function brapi_render_block($attributes) {
$ticker = $attributes['ticker'] ?? 'PETR4';
return brapi_stock_price_shortcode(['ticker' => $ticker]);
}
?>
Próximos Passos
- Veja exemplos em PHP
- Explore outros exemplos