How To Fetch Data From API In WordPress
In this tutorial, we will walk you through how to create a simple function to fetch data from an API and a shortcode to print that data out. The API we will be using in this example is the Coinbase open API and the data we will be fetching is the current price of the cryptocurrency bitcoin. If you are not familiar with APIs we highly recommend familiarizing yourself with them since they offer great fun in learning new technical skills as well as allow you to get some amazing data automatically to your WordPress. Even your own WordPress site has an open API you can access.
What is an API?
API in short is Application Programming Interface. APIs are mainly used to give access to other programs to access certain data. What makes API different from the user interface is the fact that they aren’t meant to be accessed by users but made so programs can communicate with each other. Some APIs might accept commands and give data when requested while others only accept commands or give data when requested.
Why use an API?
For example in this case we are using API to get the current price of bitcoin. Though it could as easily be the weather or a stock price. APIs help us automate the boring stuff so we don’t have to look for the data or other stuff by hand and they help us enrich the content we might be creating.
Check out our guide on “How To Automate The Boring Stuff In WordPress” for more tips on how to automate your WordPress site the easy way. Or if you wish to automate your social media check out our guide on “How To Automate Your Social Posts” to increase your social media presence and how to automate everything from posting to sharing your content on different social media platforms.
How to connect to Coinbase open API
Before we dive into printing the price of the bitcoin we need to get it. For this, we are going to connect to the Coinbase API. To do that we will be using a WordPress function called wp_remote_get. This will help us get the data from the Coinbase API.
To access the Coinbase API we will be requesting the data from an URL. The URL Coinbase so kindly offers is as follows:
https://api.coinbase.com/v2/prices/spot?currency=USD
The USD at the end of the URL is what specifies what currency we want the bitcoin price to be returned as. In this case, it will be USD. If you wish to get the price returned in a different currency, you can do so by changing the currency code. To get it in the right format you need to check the supported currency codes from the ISO 4217 standard here.
Note – The price we are accessing is the spot price. The Coinbase price endpoint has three price points that can be accessed, buy price, sell price, and spot price.
To actually get the price of bitcoin to our WordPress site we need to create the following function.
/*
* Created by https://BlogInbox.com
* Function to get the current Bitcoin price in USD from Coinbase API
*/
function get_bitcoin_price () {
// Step 1
$response = wp_remote_get('https://api.coinbase.com/v2/prices/spot?currency=USD');
// Step 2
$body = wp_remote_retrieve_body($response);
// Step 3
$value = json_decode($body);
// Step 4
foreach ($value as $key) {
return $key -> amount;
}
}
So what happens in the code? Let’s walk through it. We have marked the steps in the code for your convenience, though you can remove them if you wish.
- First, we connect to the Coinbase API and get all the information from them to our $response variable. To do this we are using the function wp_remote_get()
- After getting the response we need to clean it up so we only get the actual body part of the response. To separate the body from the response we use function wp_remote_retrieve_body().
- Now that we have just the body we can see it’s actually in JSON format so we need to decode it so we can access the data inside the array. For decoding, we use PHP’s own function json_decode() which turns the JSON into a PHP variable.
- Finally, we can return the amount to our shortcode which will then print out the bitcoin price where ever its called.
Now that we have the actual price of the bitcoin returned we still need to print it out to the page. For that, we are going to use a WordPress shortcode.
Note – It is not recommended to skip wp_remote_get because it might cause errors. It’s always preferred to retrieve the response first before retrieving the body part from the response.
How to create a WordPress shortcode
If you haven’t read our earlier post on “How To Create A Shortcode In WordPress” we highly recommend you to read it to get the basics of creating a WordPress shortcode.
To showcase the bitcoin price all we need is a simple shortcode as follows:
//Print the price of Bitcoin
add_shortcode('bitcoin', 'get_bitcoin_price');
The first part “bitcoin” is our shortcode that can be added anywhere on the site as [bitcoin] and it will print out the price of bitcoin in the currency we specified earlier (in this case USD).
Conclusions
By learning APIs and how to work with them and WordPress you can easily create new functionalities you didn’t even have earlier on. For example in this case you learned how to fetch data from the Coinbase open API, how to create a shortcode that prints out the current price of the bitcoin in USD and which you can then add anywhere on your site to showcase the price of bitcoin in real-time.
Here is the full code one more time so you can copy and paste it directly to your themes functions.php and test it out.
// Get Bitcoin spot price from Coinbase API
function get_bitcoin_price () {
$response = wp_remote_get('https://api.coinbase.com/v2/prices/spot?currency=USD');
$body = wp_remote_retrieve_body($response);
$value = json_decode($body);
foreach ($value as $key) {
return $key -> amount;
}
}
// Print the price of Bitcoin
add_shortcode('bitcoin', 'get_bitcoin_price');
After pasting the code to your current themes functions.php you can test it by writing the shortcode [bitcoin] anywhere on your page and see the spot price of bitcoin printed out on the spot of the shortcode.
What next?
To further optimize this code you could easily wrap it in a transient function so the price isn’t requested on every page load, but instead, it would be saved to your WordPress database for 1,2…12 hours before it’s again requested to ensure it doesn’t slow down your page.
If you wish to learn more about WordPress’s own API we recommend checking out the WordPress API codex, which you can find here.