Wordpress REST API

by

How to use WordPress REST API to extract posts

Recently, I needed to extract list of posts from website that was based on WordPress. It would be difficult task, if I didn’t know that newest versions of WordPress (since version 4.7) provide REST API. You can use it to extract different parts of website, like comments, posts, polls, etc.

Where to find complete description of REST API?

Complete information about all possible requests is contained in WordPress REST API documentation.

How to make requests to WordPress using jQuery?

For example, you can use GET /wp/v2/posts request when you need to extract list of posts from website as stated in documentation.  Next code will extract list of posts, if you have CORS enabled or request from the same server:

$.ajax({
      method: "GET",
      url: "http://your.website/wp-json/wp/v2/posts/",
      dataType: "json",
})
.done(function(response){console.log(response);})
.fail(function(xhr, status){console.log(status);});

Remember, CORS  must be enabled for such kind of manipulations, if you try to do AJAX request from your browser, or otherwise you will receive errors.

Read http://stackoverflow.com/a/17299796/2678487  to find how CORS affects your AJAX requests and what you can do with it.

You can enable CORS in WordPress using hack from https://joshpress.net/access-control-headers-for-the-wordpress-rest-api/. I don’t recommend it, if you don’t understand complications and security flaws that will appear after CORS enabling.

Real example

We can use next code to extract lists of posts from my blog:

Write a Comment

Comment

Webmentions

  • How to use WordPress REST API to extract posts – Full-Stack Feed

    […] Instruction of how to extract content of WordPress website like list of posts, comments and polls by using REST API requests. Read more […]