This post will go over the basics about how to use the new WordPress API to retrieve data from your site.  If you have not already read our introductory posts you can do so here.

The WordPress API can be used in many ways but within this blog post we will describe ways to retrieve basic post data from a WordPress Site.

WordPress API Endpoints

The new WordPress API comes with a lot of endpoints that you can use to perform a multitude of actions but in this post will be focusing exclusively on the /wp-json/wp/v2/posts endpoint. This endpoint will return a Javascript Object Notation (JSON) response of the posts on your site. There are a lot of parameters you can pass to this endpoint to filter and order the posts that are returned.

Here is an example request:

Setup a Connection and Call the API

For this post will be be using Javascript and jQuery to create the connection to this endpoint in order to gather the post data.  This is very simple and it only involves one single function call.

$.get("", function (posts) { /* Success - insert code here */ });

Parse the Data

Once we ping the WordPress site and retrieve all of the post data we can now parse this data and show some of the results. For this example we will console.log() each post’s HTML. Insert this code within the function above.

$.each(posts, function(index, post){ console.log(post.content['rendered']) });

Bringing it All Together

This is just a very simple example using Javascript and jQuery to console.log() some post data from any WordPress site that has the API installed. Putting it all together here is the code.

Leave a Reply

Your email address will not be published.