WordPress_blue_logo

How to use WP REST API to CRUD a post

What is WP rest API? The answer is this is a collection of JSON endpoints (URLs) to perform various operations in WordPress using any applications.

You can see the latest 10 posts json by using this type of URL: https://dilip-parmar.in/wp-json/wp/v2/posts You can check the handbook for the rest API here.

To test it, let’s do a CREATE & READ a Post using Rest API. This means we are making an Ajax request from the front end to create a new post in WP.

For that, you have to create a basic form with title & content fields, and let’s make an Ajax call to call the Rest API endpoint to create a new post & another call to view all existing posts from one category.

// Button to load all existing posts
let dynamicBtn = document.getElementById("dynamicPostsButton");

// div where all existing posts appears
let dynamicpostDiv = document.getElementById("dynamicPostsContainor");
dynamicpostDiv.innerHTML = "";

// To create new post
let submitPost = document.querySelector("button#submitPostId");
// console.log(submitPost);

submitPost.addEventListener("click", function () {
  // write ajax call to submit post now.
  let postData = {
    title: document.querySelector("#postTitleId").value,
    content: document.querySelector("#postContentId").value,
    status: "publish",
  };
  console.log(postData);
  let xhr = new XMLHttpRequest();
  xhr.open("POST", "http://localhost/Word-Plugin/wp-json/wp/v2/posts");
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.setRequestHeader("X-WP-Nonce", myData.nonce);
  xhr.onreadystatechange = function () {
    console.log(xhr.readyState);
    if (xhr.readyState == 4 && xhr.status == 200) {
      console.log(xhr.responseText);
    } else {
      console.log(xhr.response);
    }
  };
  console.log(typeof postData);
  postData = JSON.stringify(postData);
  console.log(typeof postData);
  console.log(postData);
  xhr.send(postData);
});

// Event to load all existing posts on frotend
dynamicBtn.addEventListener("click", function () {
  console.log("button is clicked to load dynamic data");
  //   make an ajax call to fetch post data
  //   init
  let xhr = new XMLHttpRequest();
  //   open
  xhr.open("GET", "https://dilip-parmar.in/wp-json/wp/v2/posts?categories=19");
  //   prepare what to do when we received or not receive the data
  xhr.onload = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      //   console.log(this);
      let responseWeGot = xhr.responseText;
      console.log(typeof responseWeGot);
      //   console.log(responseWeGot);
      let jsonData = JSON.parse(xhr.responseText);
      //   console.log(jsonData);
      console.log(typeof jsonData);
      createHTML(jsonData);
    } else {
      console.log("Some issue with this ajax call");
    }
  };
  //   send data
  xhr.send();
});

// html to create layout of existing posts
function createHTML(postData) {
  postData.forEach((element) => {
    console.log(element);
    // console.log(element.title.rendered);
    // dynamicpostDiv.innerHTML = "how you are pooja";
    dynamicpostDiv.innerHTML += "<h4>" + element.title.rendered + "</h4>";
    dynamicpostDiv.innerHTML += "<p>" + element.content.rendered + "</p>";
  });
}

To update the post you just have to change the endpoint URL with the post id

xhr.open("POST", "http://localhost/Word-Plugin/wp-json/wp/v2/posts/10");

If you want to use the ‘application password’ method for user authentication, Which is in the latest WordPress version, check this video.

Check this to know how to delete posts using REST API in WP.

The whole tutorial is here.