Rendering External API Data in WordPress Blocks on the Back End
Nov 1, 2022
DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!
This is a continuation of my last article about “Rendering External API Data in WordPress Blocks on the Front End” . In that last one, we learned how to take an external API and integrate it with a block that renders the fetched data on the front end of a WordPress site.
The thing is, we accomplished this in a way that prevents us from seeing the data in the WordPress Block Editor. In other words, we can insert the block on a page but we get no preview of it. We only get to see the block when it’s published.
Let’s revisit the example block plugin we made in the last article. Only this time, we’re going to make use of the JavaScript and React ecosystem of WordPress to fetch and render that data in the back-end Block Editor as well.
Where we left off
As we kick this off, here’s a demo where we landed in the last article that you can reference. You may have noticed that I used a render_callback method in the last article so that I can make use of the attributes in the PHP file and render the content.
Well, that may be useful in situations where you might have to use some native WordPress or PHP function to create dynamic blocks. But if you want to make use of just the JavaScript and React (JSX, specifically) ecosystem of WordPress to render the static HTML along with the attributes stored in the database, you only need to focus on the Edit and Save functions of the block plugin.
The Edit function renders the content based on what you want to see in the Block Editor. You can have interactive React components here.
The Save function renders the content based on what you want to see on the front end. You cannot have the the regular React components or the hooks here. It is used to return the static HTML that is saved into your database along with the attributes.
The Save function is where we’re hanging out today. We can create interactive components on the front-end, but for that we need to manually include and access them outside the Save function in a file like we did in the last article.
So, I am going to cover the same ground we did in the last article, but this time you can see the preview in the Block Editor before you publish it to the front end.
The block props
I intentionally left out any explanations about the edit function’s props in the last article because that would have taken the focus off of the main point, the rendering.
If you are coming from a React background, you will likely understand what is that I am talking about, but if you are new to this, I would recommend checking out components and props in the React documentation .
If we log the props object to the console, it returns a list of WordPress functions and variables related to our block:
We only need the attributes object and the setAttributes function which I am going to destructure from the props object in my code. In the last article, I had modified RapidAPI’s code so that I can store the API data through setAttributes(). Props are only readable, so we are unable to modify them directly.
Block props are similar to state variables and setState in React, but React works on the client side and setAttributes() is used to store the attributes permanently in the WordPress database after saving the post. So, what we need to do is save them to attributes.data and then call that as the initial value for the useState() variable.
The edit function
I am going to copy-paste the HTML code that we used in football-rankings.php in the last article and edit it a little to shift to the JavaScript background. Remember how we created two additional files in the last article for the front end styling and scripts? With the way we’re approaching things today, there’s no need to create those files. Instead, we can move all of it to the Edit function.
Full code
import from "@wordpress/element"; export default function Edit(props) = props; const [apiData, setApiData] = useState(null); function fetchData() , }; fetch( "https://api-football-v1.p.rapidapi.com/v3/standings?season=2021&league=39", options ) .then((response) => response.json()) .then((response) => ; // Deep clone the response data setAttributes(); // Store the data in WordPress attributes setApiData(newData); // Modify the state with the new data }) .catch((err) => console.error(err)); } return (
getData()}>Fetch data
)}
); }
I have included the React hook useState() from @wordpress/element rather than using it from the React library. That is because if I were to load the regular way, it would download React for every block that I am using. But if I am using @wordpress/element it loads from a single source, i.e., the WordPress layer on top of React.
This time, I have also not wrapped the code inside useEffect() but inside a function that is called only when clicking on a button so that we have a live preview of the fetched data. I have used a state variable called apiData to render the league table conditionally. So, once the button is clicked and the data is fetched, I am setting apiData to the new data inside the fetchData() and there is a rerender with the HTML of the football rankings table available.
You will notice that once the post is saved and the page is refreshed, the league table is gone. That is because we are using an empty state (null) for apiData‘s initial value. When the post saves, the attributes are saved to the attributes.data object and we call it as the initial value for the useState() variable like this:
const [apiData, setApiData] = useState(attributes.data);
The save function
We are going to do almost the same exact thing with the save function, but modify it a little bit. For example, there’s no need for the “Fetch data” button on the front end, and the apiData state variable is also unnecessary because we are already checking it in the edit function. But we do need a random apiData variable that checks for attributes.data to conditionally render the JSX or else it will throw undefined errors and the Block Editor UI will go blank.
Full code
export default function save(props) = props; let apiData = attributes.data; return ( <> )}
)} ); }
If you are modifying the save function after a block is already present in the Block Editor, it would show an error like this:
That is because the markup in the saved content is different from the markup in our new save function. Since we are in development mode, it is easier to remove the bock from the current page and re-insert it as a new block — that way, the updated code is used instead and things are back in sync.
This situation of removing it and adding it again can be avoided if we had used the render_callback method since the output is dynamic and controlled by PHP instead of the save function. So each method has it’s own advantages and disadvantages.
Tom Nowell provides a thorough explanation on what not to do in a save function in this Stack Overflow answer .
Styling the block in the editor and the front end
Regarding the styling, it is going to be almost the same thing we looked at in the last article, but with some minor changes which I have explained in the comments. I’m merely providing the full styles here since this is only a proof of concept rather than something you want to copy-paste (unless you really do need a block for showing football rankings styled just like this). And note that I’m still using SCSS that compiles to CSS on build.
Editor styles
/* Target all the blocks with the data-title="Football Rankings" */ .block-editor-block-list__layout .block-editor-block-list__block.wp-block[data-title="Football Rankings"] &:hover &:active } }
Front-end styles
/* Front-end block styles */ .wp-block-post-content .wp-block-football-rankings-league-table #league-standings } } } .league-table .team .team:not(:last-child) .team-logo img .stats } .last-5-games & .result-D & .result-L } }
We add this to src/style.scss which takes care of the styling in both the editor and the frontend. I will not be able to share the demo URL since it would require editor access but I have a video recorded for you to see the demo: