Skip to content

Instantly share code, notes, and snippets.

@roelmagdaleno
Last active January 21, 2022 18:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roelmagdaleno/7e0c2c66284d9eae2f08047d71d9b442 to your computer and use it in GitHub Desktop.
Save roelmagdaleno/7e0c2c66284d9eae2f08047d71d9b442 to your computer and use it in GitHub Desktop.
Show the latest cryptocurrencies in WordPress admin bar.
<?php
/*
Plugin Name: WP CoinMarketCap
Plugin URI: https://roelmagdaleno.com/
Description: Get the latest cryptocurrency data.
Version: 2.0
Author: Roel Magdaleno
Author URI: https://roelmagdaleno.com/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
function wp_cmkcap_add_admin_bar_menu( $wp_admin_bar ) {
$parent_node = array(
'id' => 'wp_cmkcap_admin_bar',
'title' => 'Cryptocurrencies',
);
$wp_admin_bar->add_node( $parent_node );
$api_endpoint = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest';
$api_args = array( 'headers' => array( 'X-CMC_PRO_API_KEY' => 'TU API DE COINMARKETCAP' ) );
$queries = array(
'start' => 1,
'limit' => 5,
'convert' => 'MXN',
);
$api_endpoint = add_query_arg( $queries, $api_endpoint );
$response = wp_remote_get( $api_endpoint, $api_args );
if ( is_wp_error( $response ) ) {
$child_node = array(
'id' => 'internal-error',
'title' => 'Internal Error - Notify the administrator.',
'parent' => 'wp_cmkcap_admin_bar',
);
$wp_admin_bar->add_node( $child_node );
return;
}
$http_code = wp_remote_retrieve_response_code( $response );
$cryptos = json_decode( wp_remote_retrieve_body( $response ), true );
if ( 200 !== $http_code ) {
$message = 404 === $http_code ? $cryptos['message'] : $cryptos['status']['error_message'];
$child_node = array(
'id' => 'api-error',
'title' => 'API Error: ' . $message,
'parent' => 'wp_cmkcap_admin_bar',
);
$wp_admin_bar->add_node( $child_node );
return;
}
foreach ( $cryptos['data'] as $crypto_data ) {
$price = number_format( $crypto_data['quote'][ $queries['convert'] ]['price'] );
$child_node = array(
'id' => 'cryptocurrency-' . $crypto_data['id'],
'title' => $crypto_data['name'] . ' / $' . $price . ' ' . $queries['convert'],
'parent' => 'wp_cmkcap_admin_bar',
);
$wp_admin_bar->add_node( $child_node );
}
}
add_action( 'admin_bar_menu', 'wp_cmkcap_add_admin_bar_menu', 999 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment