How To Integrate An External API Into Your WordPress Site

Dec 21, 2021 | WordPress | 0 comments

WordPress is a wonderfully flexible platform for creating your own website, and part of this is down to the ability to integrate third party APIs to expand the standard functionality further.
How To Integrate An External Api Into Your WordPress Site

Photo by Souvik Banerjee on Unsplash

WordPress is a wonderfully flexible platform for creating your own website, and part of this is down to the ability to integrate third party APIs to expand the standard functionality further.

If this is something you’d like to do yourself but you are not sure how to go about it, this quick guide will give you an overview of the main steps involved. That being said, we’d suggest reading through the entire guide before you start. It does require a little technical know-how, and if you find it a tad too complicated, you might want to hire a dedicated WordPress developer.

Choose an API and grab the key

You first need to know which API you want to use. There are all sorts of examples out there, from APIs which let you query Netflix’s database of movies to give recommendations to site visitors, to APIs which let you display up-to-date prices for international flights.

In order to leverage the API, you will need the key. This lets you access the data it provides, and also ensures that the API’s operator can keep track of the number of requests you make for billing purposes. All sorts of services let you effectively subscribe to APIs, with basic packages being free of charge.

Also, make sure to perform the necessary tests in production, as each time you conduct a REST API test, you will be able to see whether your integration efforts are progressing as expected, rather than only finding faults after you reach the final phase of development.

Make a child theme

For those who have a child theme available already, this is not a necessary step, but if you haven’t created one, here’s how to go about it.

First, make a folder to contain it within the same directory as your other themes. As an example, let’s call it Twenty Twenty One Child.

Next, add a new stylesheet to the folder you have created, and add the following code to it:

/*
 Theme Name:   Twenty Twenty One Child
 Template: 	twentytwentyone
 Version:  	1.0.0
*/

Then, make sure the new stylesheet is enqueued correctly, like so:

<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
    $parent_style = 'twentytwentyone-style'; // This is 'twentytwentyone-style' for the Twenty Twenty One 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')
	);
}

Now, head to the administrative dashboard and enable this theme under the Appearance menu. You can add an image at this point, uploading it to the aforementioned folder and naming it ‘screenshot.png’, although this is optional.

Make a custom template

Following on from this, we have to put together a template that will act as the underpinnings of a page for API-based interactions. First up, the header section – and for the purposes of this article, let’s go with a template for showcasing the newest movies to arrive on Netflix, as referenced earlier:

<?php
/*
Template Name: LatestNetflixReleases
*/

Save this as a .php file in the folder you made, then add a one-page template from the theme which is acting as the parent in this case:

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();

Move on to the API integration

We’re now ready to integrate the API into our template page, and in the following snippet, don’t forget to swap out your unique API key where the x’s have been used:

<?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;
}

The results will be displayed in a grid, although of course you can implement this in whatever way you please, depending on the custom theme, user interface design and layout of your site. Here’s how the template might look in full:

<?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();

Make a page using this template

Lastly, you can use WordPress to create a page with this custom template by selecting it from the dropdown in the Page Attributes section.

Again, this is just a single example of how API integration can be achieved in WordPress. Be sure to experiment yourself, test out what is possible and build something amazing!

Pin It on Pinterest

Share This