Rendering External API Data in WordPress Blocks on the Front End | CSS-Tricks

Rendering External API Data in WordPress Blocks on the Front End | CSS-Tricks

There’ve been some new tutorials popping here on CSS-Tricks for working with WordPress blocks. One of them is an introduction to WordPress block development and it’s a good place to learn what blocks are and to register them in WordPress for use in pages and posts.

While the block basics are nicely covered in that post, I want to take it another step forward. You see, in that article, we learned the difference between rendering blocks in the back-end WordPress Block Editor and rendering them on the front-end theme. The example was a simple Pullquote Block that rendered different content and styles on each end.

Let’s go further and look at using dynamic content in a WordPress block. More specifically, let’s fetch data from an external API and render it on the front end when a particular block is dropped into the Block Editor.

We’re going to build a block that outputs data that shows soccer (er, football) rankings pulled from Api-Football.

There’s more than one way to integrate an API with a WordPress block! Since the article on block basics has already walked through the process of making a block from scratch, we’re going to simplify things by using the package to bootstrap our work and structure our project.

First things first: let’s spin up a new project from the command line:

I normally would kick a project like this off by making the files from scratch, but kudos to the WordPress Core team for this handy utility!

Once the project folder has been created by the command, we technically have a fully-functional WordPress block registered as a plugin. So, let’s go ahead and drop the project folder into the directory where you have WordPress installed (probably best to be working in a local environment), then log into the WordPress admin and activate it from the Plugins screen.

Now that our block is initialized, installed, and activated, go ahead and open up the project folder from at . You’re going to want to there from the command line as well to make sure we can continue development.

These are the only files we need to concentrate on at the moment:

The other files in the project are important, of course, but are inessential at this point.

We already know that we’re using Api-Football which comes to us courtesy of RapidAPI. Fortunately, RapidAPI has a dashboard that automatically generates the required scripts we need to fetch the API data for the 2021 Premier League Standings.

If you want to have a look on the JSON structure, you can generate visual representation with JSONCrack.

I am going to wrap the RapidAPI code inside a React useEffect() hook with an empty dependency array so that it runs only once when the page is loaded. This way, we prevent WordPress from calling the API each time the Block Editor re-renders. You can check that using if you care to.

Here’s the code where I am importing , then wrapping it around the code that RapidAPI provided:

Notice that I have left the function pretty much intact, but have included a note that confirms the football standings are rendered on the front end. Again, we’re only going to focus on the front end in this article — we could render the data in the Block Editor as well, but we’ll leave that for another article to keep things focused.

Now that we are fetching data, we need to store it somewhere in WordPress. This is where the object comes in handy. We are defining the as an since the data is fetched and formatted as JSON. Make sure you don’t have any other type or else WordPress won’t save the data, nor does it throw any error for you to debug.

We define all this in our file:

OK, so WordPress now knows that the RapidAPI data we’re fetching is an object. If we open a new post draft in the WordPress Block Editor and save the post, the data is now stored in the database. In fact, if we can see it in the field if we open the site’s database in phpMyAdmin, Sequel Pro, Adminer, or whatever tool you use.

There are multiple ways to output the data on the front end. The way I’m going to show you takes the attributes that are stored in the database and passes them as a parameter through the function in our file.

I like keeping a separation of concerns, so how I do this is to add two new files to the block plugin’s folder: and (you can create a file in the directory which compiled to CSS in the directory). This way, the back-end and front-end codes are separate and the file is a little easier to read.

/explanation Referring back to the introduction to WordPress block development, there are and files for back-end and shared styles between the front and back end, respectively. By adding (which compiles to , I can isolate styles that are only intended for the front end.

Before we worry about those new files, here’s how we call them in :

Since I am using the method for the attributes, I am going to handle the enqueue manually just like the Block Editor Handbook suggests. That’s contained in the condition, and is enqueueing the two files so that we avoid enqueuing them while using the editor screen.

Now that we have two new files we’re calling, we’ve gotta make sure we are telling to compile them. So, do that in , in the section:

Another way to include the files is to define them in the block metadata contained in our file, as noted in the introduction to block development:

The only reason I’m going with the method is because I am already making use of the method.

In the rendering part, I am concentrating only on a single block. Generally speaking, you would want to target multiple blocks on the front end. In that case, you need to make use of with the block’s specific ID.

I’m basically going to wait for the window to load and grab data for a few key objects from JSON and apply them to some markup that renders them on the front end. I am also going to convert the data to a JSON object so that it is easier to read through the JavaScript and set the details from JSON to HTML for things like the football league logo, team logos, and stats.

The “Last 5 games” column shows the result of a team’s last five matches. I have to manually alter the data for it since the API data is in a string format. Converting it to an array can help make use of it in HTML as a separate element for each of a team’s last five matches.

`; // Stringify the last five match results for a team const form = team.form.split( "" ); // Loop through the match results form.forEach( ( result ) => { // Make a div for each result const resultEl = document.createElement( "div" ); // Add a class to the div resultEl.classList.add( "result" ); // Evaluate the results resultEl.innerText = result; // If the result a win if ( result === "W" ) { resultEl.classList.add( "win" ); // If the result is a draw } else if ( result === "D" ) { resultEl.classList.add( "draw" ); // If the result is a loss } else { resultEl.classList.add( "lost" ); } // Append the results to the column teamDiv.querySelector( ".form-history" ).append( resultEl ); }); tableEl.append( teamDiv ); }); });

As far as styling goes, you’re free to do whatever you want! If you want something to work with, I have a full set of styles you can use as a starting point.

I styled things in SCSS since the package supports it out of the box. Run in the command line to watch the SCSS files and compile them to CSS on save. Alternately, you can use on each save to compile the SCSS and build the rest of the plugin bundle.

Check that out — we just made a block plugin that fetches data and renders it on the front end of a WordPress site.

We found an API, -ed data from it, saved it to the WordPress database, parsed it, and applied it to some HTML markup to display on the front end. Not bad for a single tutorial, right?

Again, we can do the same sort of thing so that the rankings render in the Block Editor in addition to the theme’s front end. But hopefully keeping this focused on the front end shows you how fetching data works in a WordPress block, and how the data can be structured and rendered for display.

Images Powered by Shutterstock