Como Exibir Cotações da B3 no WordPress
Crie um shortcode personalizado para exibir cotações automáticas de ações, ETFs e FIIs em seu site WordPress.
Por Que Integrar Cotações no WordPress?
Sites financeiros, blogs de investimentos e portais de notícias precisam exibir cotações atualizadas. Com a brapi.dev, você pode:
- Exibir cotações em posts e páginas
- Atualizar automaticamente os preços
- Usar cache para performance
- Criar widgets personalizados
Implementação Básica
Adicione este código ao 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
Em Posts e Páginas
[brapi_cotacao ticker="PETR4"]
Múltiplos Ativos
Petrobras: [brapi_cotacao ticker="PETR4"]
Vale: [brapi_cotacao ticker="VALE3"]
Itaú: [brapi_cotacao ticker="ITUB4"]
Em Templates PHP
<?php echo do_shortcode('[brapi_cotacao ticker="PETR4"]'); ?>
Versão Avançada com Formatação
<?php
function brapi_stock_widget_shortcode($atts) {
$atts = shortcode_atts([
'ticker' => 'PETR4',
'show_change' => 'true',
'show_name' => 'true',
], $atts);
$ticker = $atts['ticker'];
$transient_key = 'brapi_full_' . $ticker;
$cached = get_transient($transient_key);
if ($cached !== false) {
return $cached;
}
$token = get_option('brapi_token');
$url = "https://brapi.dev/api/quote/{$ticker}?token={$token}";
$response = wp_remote_get($url, ['timeout' => 10]);
if (is_wp_error($response)) {
return '<div class="brapi-error">Erro ao carregar cotação</div>';
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (!isset($data['results'][0])) {
return '<div class="brapi-error">Cotação não encontrada</div>';
}
$quote = $data['results'][0];
$html = '<div class="brapi-stock-widget">';
if ($atts['show_name'] === 'true') {
$html .= '<div class="brapi-name">' . esc_html($quote['shortName']) . '</div>';
}
$html .= '<div class="brapi-ticker">' . esc_html($quote['symbol']) . '</div>';
$html .= '<div class="brapi-price">R$ ' . number_format($quote['regularMarketPrice'], 2, ',', '.') . '</div>';
if ($atts['show_change'] === 'true') {
$change_class = $quote['regularMarketChangePercent'] > 0 ? 'positive' : 'negative';
$change_sign = $quote['regularMarketChangePercent'] > 0 ? '+' : '';
$html .= '<div class="brapi-change ' . $change_class . '">';
$html .= $change_sign . number_format($quote['regularMarketChangePercent'], 2, ',', '.') . '%';
$html .= '</div>';
}
$html .= '</div>';
set_transient($transient_key, $html, 60);
return $html;
}
add_shortcode('brapi_widget', 'brapi_stock_widget_shortcode');
// Adicionar CSS
function brapi_enqueue_styles() {
wp_add_inline_style('wp-block-library', '
.brapi-stock-widget {
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
margin: 10px 0;
max-width: 300px;
}
.brapi-name {
font-size: 14px;
color: #666;
}
.brapi-ticker {
font-weight: bold;
font-size: 18px;
}
.brapi-price {
font-size: 24px;
font-weight: bold;
margin: 10px 0;
}
.brapi-change {
font-size: 16px;
font-weight: 600;
}
.brapi-change.positive {
color: #10b981;
}
.brapi-change.negative {
color: #ef4444;
}
');
}
add_action('wp_enqueue_scripts', 'brapi_enqueue_styles');
?>
Uso do Widget Avançado
[brapi_widget ticker="PETR4" show_change="true" show_name="true"]
Bloco Gutenberg
<?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_widget_shortcode(['ticker' => $ticker]);
}
?>
Página de Configurações
<?php
function brapi_settings_page() {
add_options_page(
'Configurações brapi',
'brapi Settings',
'manage_options',
'brapi-settings',
'brapi_settings_page_html'
);
}
add_action('admin_menu', 'brapi_settings_page');
function brapi_settings_page_html() {
if (!current_user_can('manage_options')) {
return;
}
if (isset($_POST['brapi_token'])) {
update_option('brapi_token', sanitize_text_field($_POST['brapi_token']));
echo '<div class="notice notice-success"><p>Token salvo com sucesso!</p></div>';
}
$token = get_option('brapi_token', '');
?>
<div class="wrap">
<h1>Configurações brapi.dev</h1>
<form method="post">
<table class="form-table">
<tr>
<th scope="row">
<label for="brapi_token">Token da API</label>
</th>
<td>
<input type="text"
id="brapi_token"
name="brapi_token"
value="<?php echo esc_attr($token); ?>"
class="regular-text">
<p class="description">
Obtenha seu token em <a href="https://brapi.dev" target="_blank">brapi.dev</a>
</p>
</td>
</tr>
</table>
<?php submit_button('Salvar Token'); ?>
</form>
</div>
<?php
}
?>
Boas Práticas
1. Use Cache
set_transient($cache_key, $data, 60); // Cache de 60 segundos
2. Valide Dados
$ticker = sanitize_text_field($atts['ticker']);
3. Trate Erros
if (is_wp_error($response)) {
error_log('brapi Error: ' . $response->get_error_message());
return 'Erro temporário';
}
Próximos Passos
Conclusão
Com poucos minutos você pode adicionar cotações automáticas da B3 em qualquer site WordPress. Use shortcodes para flexibilidade e cache para performance!