A Simple Guide to Using the WordPress REST API to Fetch Recent Posts

Recently, we at DiopDesign had a sit-down talk with our friends at Pitch Black https://pitchblack.au/google-ads-perth-management-lp, and we dove into the topic of the WordPress REST API. What is it? How can it be used in practical, real-world scenarios? One thing that stuck out from the conversation was a simple but useful example of the WordPress REST API: fetching recent posts from a WordPress site and displaying them on another external website.

In this article, we’re going to break down the process step by step so that anyone with basic knowledge of JavaScript and WordPress can give it a shot. Whether you’re just curious about REST APIs or you’re looking to integrate WordPress content into a different platform, this example is for you.

What Is the WordPress REST API?

Before we dive into the example, let’s get a quick understanding of what the WordPress REST API actually is. If you’re familiar with WordPress, you probably know it as a platform that powers blogs and websites, but it’s also got some pretty cool features under the hood.

The WordPress REST API is like a doorway. It allows developers to access and interact with WordPress content from outside the WordPress dashboard. So, instead of logging in and manually copying your posts or page content, you can use this API to programmatically pull in data. And that’s where REST (Representational State Transfer) comes into play. REST is just a standardized way to communicate with web services, and when we talk about the REST API in WordPress, it means that WordPress can respond to HTTP requests in a predictable way.

It’s a powerful tool because you can use it to fetch or send data without having to rely on the traditional front-end. You’re not limited to how WordPress looks or works out of the box. You can pull WordPress data into mobile apps, external websites, or even other CMS platforms.

The Use Case: Fetching Recent Posts

Alright, now that we’ve got the basic idea of the REST API out of the way, let’s move on to the fun part. The use case we’re looking at is simple: fetching recent posts from a WordPress site and displaying them on an external website. You might have a blog on WordPress and want to showcase the latest content on another platform like a portfolio site, a newsletter, or a custom-built web app.

To do this, we’ll be using the /wp-json/wp/v2/posts endpoint, which is specifically designed to grab posts from a WordPress site. With just a few lines of JavaScript, we can make an HTTP request to this API endpoint, get the data we need, and display it wherever we want.

Accessing the WordPress REST API

The first step is getting access to the WordPress REST API. The cool thing is that, for basic read operations like fetching public posts, you don’t need to worry about any complex authentication. If your WordPress site is public, the API is too (unless you’ve taken special steps to restrict it).

To access the REST API, you simply need to know your WordPress site’s URL and add /wp-json/wp/v2/posts to the end of it. Let’s say your site is example.com. The full URL to fetch your recent posts would look something like this:

https://example.com/wp-json/wp/v2/posts

When you visit that URL in a browser, you’ll see something that looks like a bunch of messy text (or JSON data, for the more familiar). This is the raw data that the REST API provides, and it includes all sorts of information about your posts: titles, content, author details, categories, and more.

You could technically read it all right there in the browser, but we’re going to take it a step further and fetch this data programmatically using JavaScript.

Fetching Recent Posts with JavaScript

Now that we know where to grab the data from, let’s look at how to actually make the request and fetch the recent posts using JavaScript.

We’ll be using the fetch() function, which is built into modern browsers and makes it super easy to make HTTP requests. If you’re new to JavaScript, don’t worry. It’s just a way of asking the API to give us the data in a structured format. Here’s an example of how this looks:

fetch('https://example.com/wp-json/wp/v2/posts')
  .then(response => response.json()) // Convert the response to JSON format
  .then(data => console.log(data))   // Log the JSON data in the console
  .catch(error => console.error('Error:', error)); // Handle any errors

When you run this code in a browser console or a JavaScript file, it will make an HTTP request to the API and print out the data in the console. This data includes an array of recent posts, and each post will have fields like title, content, link, and more.

At this stage, you can see that it’s pretty straightforward. We’re just grabbing data from a specific URL and handling it as JSON.

Parsing and Displaying the Posts

So, now that we have the raw post data, the next step is to parse it and display it in a way that makes sense to users. Let’s say you want to show the post titles as clickable links on your website.

In JavaScript, we can loop through the array of posts and dynamically create HTML elements for each one. Here’s an extended version of the previous code that adds the fetched posts to a simple list on the web page:

fetch('https://example.com/wp-json/wp/v2/posts')
  .then(response => response.json())
  .then(posts => {
    const postList = document.getElementById('post-list'); // Target the <ul> in our HTML

    posts.forEach(post => {
      const listItem = document.createElement('li'); // Create a new list item
      listItem.innerHTML = `<a href="${post.link}">${post.title.rendered}</a>`; // Add post link
      postList.appendChild(listItem); // Append it to the <ul>
    });
  })
  .catch(error => console.error('Error:', error));

In this code, we first grab the element with the ID post-list (which could be a <ul> element in your HTML). Then, for each post in the API response, we create a new list item (<li>) and insert the title of the post as a clickable link. Finally, we append that list item to the post-list element, so it’s displayed on the page.

Sample HTML Structure

You might be wondering where the JavaScript fits into your website. Here’s a simple HTML page where you can plug in the above code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Recent Posts</title>
</head>
<body>

  <h1>Latest Blog Posts</h1>
  <ul id="post-list"></ul>

  <script src="script.js"></script> <!-- Your JS file containing the fetch code -->

</body>
</html>

When you run this page, it will display a list of recent posts from the WordPress site, with each post title linking to the actual article.

Embedding the Code in an External Website

Once you have the JavaScript code ready, embedding it into an external website is just a matter of placing it into the <script> tags of your HTML, as we saw in the previous section. But if you’re working with a live website, there are a few things you might want to keep in mind to ensure everything runs smoothly.

If your website is using a CMS like WordPress or any other framework, you can usually inject the script either in the footer of your theme, or through a specific area designated for custom scripts. In WordPress, for example, you could add the JavaScript directly into your theme’s footer.php or use a plugin like Insert Headers and Footers to include it.

One important thing to note is that the JavaScript file should be loaded after the DOM (Document Object Model) is fully constructed. That way, when the script looks for the post-list element, it already exists on the page. You can either put the script at the bottom of your HTML, just before the closing </body> tag, or use the DOMContentLoaded event to ensure that your script only runs after the page has fully loaded. Here’s how you can do that:

document.addEventListener('DOMContentLoaded', function () {
  fetch('https://example.com/wp-json/wp/v2/posts')
    .then(response => response.json())
    .then(posts => {
      const postList = document.getElementById('post-list');

      posts.forEach(post => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `<a href="${post.link}">${post.title.rendered}</a>`;
        postList.appendChild(listItem);
      });
    })
    .catch(error => console.error('Error:', error));
});

This ensures that your code will work even if the script is placed in the head of the document.

Handling API Errors and Edge Cases

While this example works in a straightforward scenario, it’s important to think about potential issues or edge cases that might arise when working with an API. Since we’re dealing with a network request, there’s always a chance things might not go perfectly every time.

For example, the WordPress REST API might be down, the URL could be incorrect, or there could be a problem with the server. That’s why error handling is key. In the code we’ve already seen, we included a .catch() block at the end of the fetch request to catch any errors that happen during the API call. You might want to enhance this by showing a message on the page if the posts fail to load, rather than just logging the error in the console.

Here’s how you can update the code to display a friendly error message to users:

document.addEventListener('DOMContentLoaded', function () {
  fetch('https://example.com/wp-json/wp/v2/posts')
    .then(response => response.json())
    .then(posts => {
      const postList = document.getElementById('post-list');

      posts.forEach(post => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `<a href="${post.link}">${post.title.rendered}</a>`;
        postList.appendChild(listItem);
      });
    })
    .catch(error => {
      const postList = document.getElementById('post-list');
      postList.innerHTML = '<li>Sorry, we couldn’t load the posts at this time.</li>';
      console.error('Error:', error);
    });
});

This way, if something goes wrong with the API call, the user sees a meaningful message instead of an empty page.

Additional Considerations: CORS and Security

As you start to experiment more with the WordPress REST API, there are a couple of additional considerations to keep in mind, especially around Cross-Origin Resource Sharing (CORS) and security.

CORS (Cross-Origin Resource Sharing)

When you fetch data from a different domain (like fetching posts from example.com to display on anotherwebsite.com), you might run into something called CORS. This is a security feature in browsers that prevents web pages from making requests to domains other than their own, unless the target server specifically allows it.

In most cases, WordPress allows CORS for basic requests, but if you’re working in a more controlled environment or using a custom setup, you might run into CORS errors. If that happens, you can either adjust the CORS settings on the WordPress server or use a proxy to fetch the data.

Security

We’ve kept things simple in this use case by fetching publicly accessible posts, which don’t require any authentication. But what if you want to access private or protected content, like drafts or posts behind a login? In that case, you’ll need to authenticate your API requests.

WordPress supports various authentication methods, including cookie-based authentication for logged-in users and token-based authentication (such as JWT or OAuth) for external applications. If you’re looking to dive deeper into more complex use cases, you’ll want to explore those options.

But for now, for public data, the setup we’ve covered works perfectly.

Conclusion

The WordPress REST API opens up a lot of possibilities, even in its most basic form. In this example, we’ve seen how easy it can be to fetch recent posts from a WordPress site and display them on another website. With just a few lines of JavaScript and a basic understanding of the REST API, you can extend your WordPress content beyond the traditional confines of your theme and dashboard.

From here, the sky’s the limit. You could customize how the data is displayed, pull in additional post details like featured images or categories, or even build entire apps or sites that interact with WordPress content in real time.

We hope this introduction was helpful, and if you have any questions, feel free to reach out! The REST API is a great tool, and the more you experiment with it, the more you’ll see its potential. Stay tuned for more tips and deeper dives into the world of WordPress and development!