How to Integrate an External API in a WordPress Page
In a previous post, we walked through an example of calling an external API from WordPress using a plugin. The plugin then populated a widget. This time we will create a custom page template that will show results from an API call. To change the WordPress theme we will create a child theme and add the page template in the child theme.
WordPress and External APIs – Theme versus Plugin Integration
WordPress is a versatile platform for developing applications. There are two main areas within WordPress to integrate external APIs. The two options are the Themes and Plugins. Themes are like houses for your website, Plugins are like cars. Your site can only live in one Theme at a time, but it can use many plugins at once.
Theme modifications involve fewer steps than creating a new plugin. Child themes are a safe way to customize your site independent of the parent theme. That means you can install parent theme updates without losing your changes. To change how a page looks in WordPress it makes sense to use a child theme.
WordPress Theme Modification to Integrate an External API
In the current environment of health concerns, people have not been able to go to movie theaters. For this reason, many video streaming services have become very popular. My in-laws like to take our kids to the movies a couple of times per month. Since that is not an option I suggested the kids go to their house. They have a big television so it would be like a theater. Also, no strangers would complain if the kids got up and wandered around while the movie was playing. For this article, we will integrate an external API into a WordPress page. This page will show the latest movies added to Netflix. Now we get to the actual steps, which assume a WordPress site is already setup.
- Get an API Key for the REST API
- Create a child theme
- Create a custom page template
- Integrate the API into your page template
- Add a new page using your new page template
Step 1. Get an API Key for the REST API
The API we will use for this article is the Next Generation Netflix Global Search. We will use it to display up to 100 of the most recent items added to Netflix. The pricing is very simple, as shown below. You only need to pay anything if you call the API more than 100 times in a day.
If this is your first time using a RapidAPI, you’ll need to create a free account. You can create a free RapidAPI account by clicking the Sign-Up button at the top right of the screen. You can see this Sign Up button when looking at any of the thousands of APIs available. The account gives you quick access to subscribe to any of the over 10 thousand APIs at rapidapi.com.
Step 2. Create a child theme
Next, we need to make sure a child theme is available in our WordPress site. If you already have a child theme, skip to step 3. Following theme instructions from WordPress we will take the following steps:
- Create a child theme folder. Let’s say your current theme folder is wp-content/themes/twentytwenty/. You’ll want to make another folder in the same directory. Name the new folder twentytwenty-child.
- Create a stylesheet called style.css for your child theme (in your new folder). You need this file even if it only contains the following code. Version is not required but it allows you to clear the cache when making changes later by changing it.
/* Theme Name: Twenty Nineteen Child Template: twentynineteen Version: 1.0.0 */
- Enqueue stylesheet. Do this in a functions.php file in your new child theme folder. Here is the example from the WordPress instructions modified for this example.
<?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { $parent_style = 'twentynineteen-style'; // This is 'twentynineteen-style' for the Twenty Nineteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); }
- Activate child theme. Do this in the WordPress admin area under Appearance->Themes.To add an image for the child theme you’ll need capture an image and upload it to your child theme folder. The name of the file has to be screenshot.png.
Step 3. Create a custom page template
Once we have a child theme in place, we will add a custom page template to interact with the API. This is the next step after activating the child theme in the WordPress instructions. We will start with the required header section:
<?php /* Template Name: LatestNetflixReleases */
This will be a new file called LatestNetflixReleases.php. Save this new file in the /wp-content/themes/twentynineteen-child/ folder. Once we have a filename and location, let’s copy over the single page template for the parent theme. This is from /wp-content/themes/twentynineteen/page.php:
get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main"> <?php // Start the Loop. while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content/content', 'page' ); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) { comments_template(); } endwhile; // End the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_footer();
Step 4. Integrate the API into your page template
Once we have that code as a starting point we will pull out the loop and add the REST API integration. Starting with the PHP Curl sample code for the API we have the following. Replace the x’s with your API key:
<?php $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://unogsng.p.rapidapi.com/genres", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "x-rapidapi-host: unogsng.p.rapidapi.com", "x-rapidapi-key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; }
Then to display the results, we will decode the JSON returned from the API. This will give us an array of objects which we will loop through and populate into a grid. In the example I used custom classes to define the grid. You don’t need that if your site uses bootstrap or another responsive UI framework. The final page template file will look like this (again replace the x’s with your API key):
<?php /* Template Name: Latest Netflix Releases Description: this is a custom page template which will use a third party API to pull a list of up to 100 items released on Netflix within the last 7 days. */ //This is used to tell the API what we want to retrieve $lastWeek = date("Y-m-d",time()-(24*3600*7)); //Show the header of your WordPress site so the page does not look out of place get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main"> <?php $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://unogsng.p.rapidapi.com/search?newdate=$lastWeek&orderby=date&audio=english", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "x-rapidapi-host: unogsng.p.rapidapi.com", "x-rapidapi-key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { if ($debug) echo "cURL Error #:" . $err; else echo "Oops, something went wrong. Please try again later."; } else { //Create an array of objects from the JSON returned by the API $jsonObj = json_decode($response); //Reorder the items so the newest releases are first $newestReleasesFirst = array_reverse($jsonObj->results); //Create a simple grid style for the listings $pageCSS = "<style> .netflix-wrapper{ display:grid; grid-template-columns: 200px 200px 200px; } .show-wrapper{padding:10px;} </style>"; //Create the WordPress page content HTML $pageHTML="<h2>Netflix releases since $lastWeek (in English)</h2>"; $pageHTML.="<div class='netflix-wrapper'>"; //Loop through the API results foreach($newestReleasesFirst as $showObj) { //Put each show into an html structure // Note: if your theme uses bootstrap use responsive classes here $pageHTML.="<div class='show-wrapper'>"; //Not all items have a 'poster', so in that case use the img field if (!empty($showObj->poster)) $thisImg = $showObj->poster; else $thisImg = $showObj->img; //Show the image first to keep the top edge of the grid level $pageHTML.="<img style='max-width:166px;float:left;' src='".$thisImg."' />"; $pageHTML.="<h3>".$showObj->title."</h3>"; $pageHTML.="<span>added to netflix ".$showObj->titledate."</span>"; $pageHTML.="<div style='float:left;'>".$showObj->synopsis."</div>"; $pageHTML.="</div>"; } $pageHTML.="</div>"; echo $pageCSS.$pageHTML; } // end of check for curl error ?> </main><!-- #main --> </div><!-- #primary --> <?php //Show the footer of the WordPress site to keep the page in context get_footer();
Step 5. Add a new page using your new page template
Within the WordPress admin area you will see your custom page template as an option when adding a new page.
Select your custom template to add this new custom page with the external API integrated. The final result of this example will look something like the image below. Your site header will be above it and your footer will be below the last line of releases.
Conclusion
In this article, we have walked through a simple example to show Netflix releases on a WordPress page. We used an external API within a custom page template to pull the releases. This page template was then chosen for a new page within the WordPress admin area. Apply some basic CSS to put the releases into a grid display. The sort order I applied depends on the latest release date within Netflix. The two filters we used as API parameters were the ‘newdate’ and ‘audio’ language. If you want the latest releases in French you would change the audio filter. If you want a different sort order you can specify that in the ‘orderby’ parameter.
You can use this process can to integrate any REST API into a WordPress Page. Use your imagination and the sky is the limit!
Finocia says
Thank you so much, it’s so helpful. And also it’s simple and easy to understand
Robert Davis says
You’re welcome! I’m glad you found it helpful and understandable.
Fernando says
Congratulations about your post.
Can you tell me if exist some plugin that capture json file format and transform to an HTML or PHP formated page? in another words it’s always necessary work with programming language to fech this files to expose in a post page?
Robert Davis says
Hi Fernando,
I don’t know of a plugin which would automatically convert JSON to HTML. In order for a plugin like this to be useful, 2 parts would need to be standardized:
1) The actual JSON would need to be the same structure in order for a plugin to recognize the elements properly.
2) The actual format to display the results in would need to be the same.
Yes you could create a plugin to do this, but it would only be useful for one type of data source and one display format.
Regards,
Robert
Allan says
Thank you for this post. I will try it. Question, how do you make the movie clickable and open in a new tab/windows to get more information about that movie? Also how do you add basic authentication to this? Thank you.
Robert Davis says
Hi Allan,
Making the movie clickable to open in a new tab or window can be achieved by changing the template (line 74 in the example page template above) to wrap each image in an anchor tag with a target of “new”. As far as populating the new window with movie details, you might look into an api for imdb.com to help with that.
For basic authentication there are many ways to achieve that in the context of a WordPress page. You could start with a free plugin like one of those listed at https://wordpress.org/plugins/tags/authentication/ for example.
Regards,
Robert
abby Group says
I am learning the curve here. Do you have a plugin template for all? . I meant a template of plugin code that i can change to use for any API . I intend to use it in WordPress.
I saw the one for weather and because i am rookie, i do not know what to remove and use same for covid19.
Thanks
Abby
Robert Davis says
Hi Abby,
You could use the template on this page as an example for a WordPress page. You could use the example API call from a WordPress plugin if you want to make a plugin. In each case, simply update these items:
1) The endpoint of each API is unique
2) Use your own API credentials
3) Include any required input parameters for the API you want to use
4) Handle the output according to what you are expecting from the API you want to use
Regards,
Robert
Samuel Afoakwah Afranie says
Hi can this work for football API?
Robert Davis says
Hi Samuel,
Yes it can work for a football API like the one at https://rapidapi.com/api-sports/api/api-football. There are no pictures retrieved from that API but you could list win/loss statistics of each team in a schedule of upcoming games instead. Have fun with that!
Regards,
Robert
marty says
Hi I am new to this, can you tell me why my test page shows up the way it does in the link?
https://mcginleysoil.co.uk/index.php/test-page/
Thanks
Marty
Robert Davis says
Hi Marty,
It looks to me like the get_footer() function is being called before printing the JSON results of the API call and then adding the example code above. Are you using a custom page template for that test post? If so, make sure get_footer() is only called at the end of the file and do not echo the JSON results of the API directly to the page.
Regards,
Robert
Isaac Opoku says
Hi Robert Davism
I seriously need your help. I am building my online market with no money. I have been able to set up my online market and recently meet a supplier who want to assist me. he gave me his API to connect my site to his but iI little knowledge in coding. Can you help help me connect my online market to my supplier through the API credential given. In other to make my online complete and be competitive in Ghana. I hope it touches your heart. Thanks in advance
Isaac Opoku says
Hope to hear from u soon
Ria says
Hello, this is a nice tutorial. I’m working on localhost and can you tell me where to display the 2 codes as seen on step 4? is it on the parent page or the child theme../ I’m getting a WordPress error after publishing.
Robert Davis says
Hi Ria,
Thanks for your comment. The 2 codes seen on step 4 go into the custom page template in your child theme. What error are you seeing?
Regards,
Robert
Mr. Chris says
I actually followed you but, i got lost along the way.
The Step 4. Integrate the API into your page template, got me confused.
i don’t really know which file in the child team to put the code.
Robert Davis says
Hello Mr. Chris,
Step 3 is where you create the custom page template file you will be modifying in step 4. The path is mentioned as an example in step 3. Once you have the file with the Template Name comment in the header saved in your child theme folder, you’ll then see the new template name. This will appear as a page template option in WordPress when you create a new page.
Regards,
Robert
Divine Pumah says
Hello Robert,
Thank you for creating this article. Very helpful. I ran into this article because I have been researching how to get the api-football(subscribed to a plan already) integrated into my soccer website to display features like livescores, standings etc. I have just a beginner coding knowledge and no experience working with APIs. I am aiming for something similar to goal.com. Is this achievable and if you don’t mind would you brief me on the steps to follow?
Robert Davis says
Hello Divine Pumah,
The steps you would take really depend on how your soccer website is setup. If it is a WordPress site you could follow a similar procedure as what I outlined in this article. You would use a collection of API calls to pull the different information you want from api-football. Then you would populate the page template with the data in whatever order you want.
Regards,
Robert
Dustin Hartuv says
You guys have a great site 🙂 Really clear and easy to understand articles.
Robert Davis says
Hi Dustin,
Thanks for the compliments. I’m glad you find the articles helpful.
Regards,
Robert
Ken Metheny says
Definite learning curve here, as I’m still weak in PHP as well. I am attempting to connect to an API that authenticates differently — apparenting it is not Rapid API, but I could be wrong. The cURL looks like this:
curl -X GET “https://xxx” -H “accept: application/json” -H “x-functions-key: xxxx” I redacted the actual site and API key just in case they don’t want it publicized. I’m trying to figure if the only line I change is the HTTPHEADER array to “x-functions-key: xxxx”
Are there different forms of APIs with different types of authentication?
Robert Davis says
Hi Ken,
Yes you are on the right track. But it looks like you need two elements in the HTTPHEADER array, one for the accept: application/json and the other for the x-functions-key.
Yes there are different forms of APIs with various authentication types. Take a look at https://rapidapi.com/blog/api-glossary/what-is-json-api-json-vs-graphql-vs-rest-api-comparison/ to see how others compare to REST.
Regards,
Robert
James Emmanuel says
Hi Robert Davis , can the example codes work with dingconnect API? because i am trying to integrate Ding mobile recharge to a wordpress site, then come accrosss your post.
Robert Davis says
Hi James,
According to their website the dingconnect api is a REST service so you should be able to integrate it the same way as the examples in this article.
Regards,
Robert
Enoch Boateng says
Robert this very helpful and informative,
Thank you. I also have a very similar project with dingconnect API just like James Emmanuel. @James Emmanuel have you been able to solve it?
@Robert please I would appreciate if you can give it a look and help shed more light on how we can integrate dingconnect api the same way as the Netflix example.
Thanks.
Robert Davis says
Hi Enoch,
I checked the documentation for dingconnect. Although there is a list of methods at https://www.dingconnect.com/Api/ there are no example request bodies that I can find, only responses. You might need to have an account and be logged in to see the requests. Once you find the request examples you could model your interface after them for the methods you need. But if you are providing a service to people there will be multiple API interactions, not just one as described in this article.
Regards,
Robert
Facundo says
Great article dear Robert!
I have a question: i need to do that but i need to insert the API data inside Post’s fields (like pages or portfolio). Should I edit Portfolio template for example? (in place of create a new page template). Or what you recommend?
Thank you very much!
Robert Davis says
Hi Facundo,
If you want to insert the API data into a Post, then you could edit the template for the type of Post you want to edit. If that is a Portfolio, then yes edit that. Just make sure you do it in a child theme.
Regards,
Robert
Jose says
I a confused in step 4. where should I put PHP Curl sample code on the single page template for the parent theme. i mean the starting or ending of the existing code?
Robert Davis says
Hi Jose,
The curl code can be put near the top of the single page template. Just make sure it is above where you start printing API data to the page.
Regards,
Robert