Add a Dashboard Widget to Display Cryptocurrency Prices
Home » WordPress » How to Add a Dashboard Widget in WordPress to Display Cryptocurrency Prices

How to Add a Dashboard Widget in WordPress to Display Cryptocurrency Prices

How to Add a Dashboard Widget in WordPress to Display Cryptocurrency Prices – This tutorial will guide you through adding a dashboard widget in WordPress to display a table of cryptocurrency prices fetched from the CoinCap API.

The table will be made responsive and interactive using the Datatables library. We’ll also ensure the code handles API errors gracefully.

A Step-by-step Tutorial to Create a Dashboard Widget for Cryptocurrency Prices in WordPress

In this section, we’ll cover the entire process, from enqueuing the necessary assets to fetching data from the CoinCap API and displaying it in a WordPress dashboard widget.

Also read: How to Create an AI Featured Image Generator WordPress Plugin

Prerequisites

Before we begin, ensure you have:

  • A working WordPress installation.
  • Access to edit the functions.php file of your theme or a site-specific plugin.

Step 1: Setting Up Your Environment

We’ll start by enqueuing the necessary CSS and JS files for Datatables, which will provide the interactive table functionality.

Enqueuing Datatables Assets

First, we need to enqueue the Datatables CSS and JS files in the WordPress admin area.

function zerobytecode_enqueue_datatables_assets() {
    echo '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/2.0.7/css/dataTables.dataTables.min.css">';
    echo '<script type="text/javascript" src="//cdn.datatables.net/2.0.7/js/dataTables.min.js"></script>';
}
add_action('admin_head', 'zerobytecode_enqueue_datatables_assets');

Step 2: Writing the Code to Fetch and Display Data

Next, we’ll write functions to fetch cryptocurrency prices from the CoinCap API and display them in a dashboard widget.

Fetching Cryptocurrency Prices

We’ll create a function to fetch cryptocurrency prices from the CoinCap API. This function will handle potential errors and format the data for display.

function zerobytecode_fetch_crypto_prices() {
    $api_url = 'https://api.coincap.io/v2/assets';
    $args = array(
        'headers' => array(
            'Accept' => 'application/json',
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
        )
    );
    $response = wp_remote_get($api_url, $args);
    if (is_wp_error($response)) {
        error_log('Error fetching data from CoinCap API: ' . $response->get_error_message());
        return ['error' => 'Failed to fetch data from CoinCap API.'];
    }
    $data = json_decode(wp_remote_retrieve_body($response), true);
    if (!isset($data['data'])) {
        error_log('Invalid response structure from CoinCap API.');
        return ['error' => 'Invalid response structure from CoinCap API.'];
    }
    $coins = ['bitcoin', 'ethereum', 'solana'];
    $crypto_prices = [];
    foreach ($data['data'] as $coin) {
        if (in_array($coin['id'], $coins)) {
            $crypto_prices[] = [
                'name' => $coin['name'],
                'symbol' => $coin['symbol'],
                'price' => number_format((float)$coin['priceUsd'], 2),
                'change' => number_format((float)$coin['changePercent24Hr'], 2) . '%',
            ];
        }
    }
    return $crypto_prices;
}

Displaying Cryptocurrency Prices in a Dashboard Widget

We’ll create a function to display the fetched cryptocurrency prices in a dashboard widget. This function will also initialize Datatables for the table.

function zerobytecode_crypto_dashboard_widget() {
    $crypto_prices = zerobytecode_fetch_crypto_prices();
    if (isset($crypto_prices['error'])) {
        echo '<p>' . esc_html($crypto_prices['error']) . '</p>';
        return;
    }
    echo '<table id="crypto-prices" class="display">';
    echo '<thead><tr><th>Name</th><th>Symbol</th><th>Price (USD)</th><th>24h Change</th></tr></thead>';
    echo '<tbody>';
    foreach ($crypto_prices as $crypto) {
        echo '<tr>';
        echo '<td>' . esc_html($crypto['name']) . '</td>';
        echo '<td>' . esc_html($crypto['symbol']) . '</td>';
        echo '<td>' . esc_html($crypto['price']) . '</td>';
        echo '<td>' . esc_html($crypto['change']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';
    echo '<script> jQuery(document).ready(function($) { $("#crypto-prices").DataTable(); }); </script>';
}

Step 3: Registering the Dashboard Widget

Finally, we’ll register the dashboard widget with WordPress.

function zerobytecode_register_crypto_dashboard_widget() {
    wp_add_dashboard_widget('zerobytecode_crypto_dashboard_widget', __('Crypto Prices', 'zerobytecode'), 'zerobytecode_crypto_dashboard_widget');
}
add_action('wp_dashboard_setup', 'zerobytecode_register_crypto_dashboard_widget');

Download and Install It as a WordPress Plugin

Now we’ve successfully created a WordPress admin dashboard widget to display cryptocurrency prices. You can save the following code and use it as a plugin:

<?php
/**
 * Plugin Name: Cryptocurrency Prices Dashboard Widget
 * Plugin URI: https://zerobytecode.com/add-a-dashboard-widget-in-wordpress-to-display-cryptocurrency-prices/
 * Description: Add a WordPress admin dashboard widget to display Cryptocurrency Prices.
 * Version: 1.0.0
 * Author: ZeroByteCode
 * Author URI: https://zerobytecode.com/
 * Text Domain: zerobytecode
 */
if (!defined('ABSPATH')) exit; // Exit if accessed directly

// Enqueuing Datatables Assets
function zerobytecode_enqueue_datatables_assets() {
    echo '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/2.0.7/css/dataTables.dataTables.min.css">';
    echo '<script type="text/javascript" src="//cdn.datatables.net/2.0.7/js/dataTables.min.js"></script>';
}
add_action('admin_head', 'zerobytecode_enqueue_datatables_assets');

// Fetching Cryptocurrency Prices
function zerobytecode_fetch_crypto_prices() {
    $api_url = 'https://api.coincap.io/v2/assets';
    $args = array(
        'headers' => array(
            'Accept' => 'application/json',
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
        )
    );
    $response = wp_remote_get($api_url, $args);
    if (is_wp_error($response)) {
        error_log('Error fetching data from CoinCap API: ' . $response->get_error_message());
        return ['error' => 'Failed to fetch data from CoinCap API.'];
    }
    $data = json_decode(wp_remote_retrieve_body($response), true);
    if (!isset($data['data'])) {
        error_log('Invalid response structure from CoinCap API.');
        return ['error' => 'Invalid response structure from CoinCap API.'];
    }
    $coins = ['bitcoin', 'ethereum', 'solana'];
    $crypto_prices = [];
    foreach ($data['data'] as $coin) {
        if (in_array($coin['id'], $coins)) {
            $crypto_prices[] = [
                'name' => $coin['name'],
                'symbol' => $coin['symbol'],
                'price' => number_format((float)$coin['priceUsd'], 2),
                'change' => number_format((float)$coin['changePercent24Hr'], 2) . '%',
            ];
        }
    }
    return $crypto_prices;
}

// Displaying Cryptocurrency Prices in a Dashboard Widget
function zerobytecode_crypto_dashboard_widget() {
    $crypto_prices = zerobytecode_fetch_crypto_prices();
    if (isset($crypto_prices['error'])) {
        echo '<p>' . esc_html($crypto_prices['error']) . '</p>';
        return;
    }
    echo '<table id="crypto-prices" class="display">';
    echo '<thead><tr><th>Name</th><th>Symbol</th><th>Price (USD)</th><th>24h Change</th></tr></thead>';
    echo '<tbody>';
    foreach ($crypto_prices as $crypto) {
        echo '<tr>';
        echo '<td>' . esc_html($crypto['name']) . '</td>';
        echo '<td>' . esc_html($crypto['symbol']) . '</td>';
        echo '<td>' . esc_html($crypto['price']) . '</td>';
        echo '<td>' . esc_html($crypto['change']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';
    echo '<script> jQuery(document).ready(function($) { $("#crypto-prices").DataTable(); }); </script>';
}

// Registering the Dashboard Widget
function zerobytecode_register_crypto_dashboard_widget() {
    wp_add_dashboard_widget('zerobytecode_crypto_dashboard_widget', __('Crypto Prices', 'zerobytecode'), 'zerobytecode_crypto_dashboard_widget');
}
add_action('wp_dashboard_setup', 'zerobytecode_register_crypto_dashboard_widget');

Simply upload it into your WordPress site and activate the plugin.

Wrapping Up

By following these steps, you have successfully added a dashboard widget in WordPress that displays a table of cryptocurrency prices fetched from the CoinCap API.

The widget uses Datatables for a responsive and interactive table experience and handles API errors gracefully. This setup can be further customized and expanded to suit more specific needs or to fetch additional data.

Similar Posts