Thursday, March 7, 2019

Getting wordpress posts using REST API

Below is a function to get the posts from a WordPress website:

function getNews() {
  const apiRoot = "https://test.site/wp-json";
  var wp = new WPAPI({ endpoint: apiRoot });
  wp.posts()
    .perPage(3)
    .then(posts => {
      posts.forEach(function(post) {
        console.log(post.content.rendered);
      });
    })
    .catch(err => {
      console.log("Error: " + err);
    });
}


You need to reference the wp api library in order to work:

<script src="wpapi/wpapi.min.js"></script>

The wpapi can be downloaded from:

http://wp-api.org/node-wpapi/


No comments:

Post a Comment