WordPress REST API Tutorial: Fetch Blog Posts by WP REST API

Complete WordPress REST API tutorial series link.

WordPress is highly extensive and provides long-term support for the development. This is why WP is having the largest market share on the web. In the last few version updates, WordPress inbuilt some of the technological advances to its core and REST API support is one of them.

With upcoming version 5, it is going to implement Gutenberg editor with its core, which is based on React JS. If you wish to know more about Gutenberg development follow this tutorial.

Previously you have learned how to create a post from frontend using WP REST API. In this tutorial, you’ll learn to fetch posts data using WP REST API. By implementing this, we can create decoupled applications with the help of WordPress.


For this our API endpoint is http://yourwebsite.com/wp-json/wp/v2/posts. By visiting this URL for our domain or WP local install we can see it is returning JSON data for posts. Also, we can add different arguments to this URL to customize our request as per our requirement.

By default, this URL will return posts JSON data in descending order. But by adding an argument with this URL we customize the order of the result. To order our post data by ascending order we need to add ?order=asc  to our API endpoint. So the final URL will be http://yourwebsite.com/wp-json/wp/v2/posts?order=asc.

To search for posts containing specific strings of text we can add ?search=search+strings to our URL. Then the complete URL will be http://yourwebsite.com/wp-json/wp/v2/posts?search=search+strings. You can learn more about arguments from REST API handbook here.

Creating Our Application

After a brief introduction now its time to get our hands dirty with some real code. To make it simple I’ll show it in WordPress theme. But you can use the codes anywhere you want. Here I’ll create a button on a page which will trigger a function to load our posts from our WP site.

So first we will create a page template in our theme and we will add the code over there mentioned below.

	<button id="posts-btn">Load Post Data</button>
	<div id="posts-container"></div>

Here, I have created a button with the id of “posts-btn”, this id will help us to track click event of the button. Below the button I have added an empty div with another id of “posts-container”, this div element will contain all our posts generated from WP REST API.

Now we will create a JS file which will handle our request and generate the posts from REST API. So here I have created a directory called /js/ and with that directory, I have created a file called api-main.js. After creating the file add the code below to it.

var PostsBtn = document.getElementById("posts-btn");
var PostsContainer = document.getElementById("posts-container");

if( PostsBtn ) {
    PostsBtn.addEventListener("click", function(){
        var ourRequest = new XMLHttpRequest();
        ourRequest.open('GET', 'http://localhost/wp-rest/wp-json/wp/v2/posts?order=asc');
        ourRequest.onload = function() {
            if(ourRequest.status >= 200 && ourRequest.status < 400) {
                var data = JSON.parse(ourRequest.responseText);
            } else {
                console.log('We connected to the server, but it returned an error.');

        ourRequest.onerror = function() {
            console.log('Connection error');


This is our main function which fires when we click on the button we created on our page template previously. At first, I have created 2 variables which hold those 2 elements in our page template. From line 5, our button click function started, then ourRequest is an object that can handle HTTP requests.

At line 8, I’m sending GET request to my local WP install and I want to get posts in ascending order. You should replace http://localhost/wp-rest/ with your domain name or local WP install. Then, when our request is handled by the API we will get some status from our server. If the status is between 200 to 400 then it should work properly. Then we store our response data in a data variable and pass it to another function which will populate the HTML from raw JSON data. After this, I have handled a few errors if something goes wrong.

Now we should create the createHTML function to complete work on this file. So add the code below to this file.

function createHTML( postsData ) {
    var ourHTMLString = '';
    for( var i = 0; i < postsData.length; i++) {
        ourHTMLString += '<h2>' + postsData[i].title.rendered + '</h2>';
        ourHTMLString += postsData[i].content.rendered;

    PostsContainer.innerHTML = ourHTMLString;

This function gets postsData which we passed as data previously. Now for every post, we will add HTML elements to ourHTMLString variable.

posts api response

If we see our JSON data properly, then we can see that our actual title and content is located at rendered object of those respective JSON object. So in output, I have added those values to our output variable.

Now, most of our work is done. The only thing is left is to connect this api-main.js file with the frontend of our site. To do this add the code below to our theme functions.php file.

add_action( 'wp_enqueue_scripts', 'enqueue_api_script' );

function enqueue_api_script() {
   wp_enqueue_script( 'api-main-js', get_template_directory_uri() . '/js/api-main.js', NULL, 1.0, true );

After connecting the JS file, now we can fetch our blog posts using WP REST API by just clicking on a button.

You can implement this code for any application written in any language. As the main API handling code is written in JS, you have code that works on any almost environment.

I hope this tutorial helped you understand WordPress REST API more.

If you have any questions, query & suggestions, then let me know by comment down below.

Happy coding 🙂

Complete WordPress REST API tutorial series link.



Leave a Reply

Your email address will not be published. Required fields are marked *