Connecting Frontend to the REST API
Learn using a nonce for authenticating a request to modify data.
REST API /lecture endpoint
In the lesson on search functionality, we explored the default WordPress REST API in detail. The default REST API has links for different post types. Since we enabled the show-in-rest
option when registering the lecture
post type, we can view the JSON data for the ten most recent lecture note posts by adding /wp-json/wp/v2/lecture to the end of the root URL of the website.
This URL provides all the information about the lecture posts like the ID of the post, author ID and its content etc. We can use the ID at the end of the URL to view the information about a specific lecture post.
The ID of the first post in our case is 83. When this ID is used at the end of the root URL as /wp-json/wp/v2/lecture/83, we get raw JSON data for that one post. This is an example of a GET request to the REST API. We can also send a ZPUT request to the same URL to update the post and a DELETE request to remove the post from the WordPress database.
Update a lecture
A PUT HTTP request is used to edit an existing resource on the server. When the user clicks the Save button, we will send a PUT HTTP request. Unlike the GET request where we only need to provide the URL of the API, here we also need an object describing the request.
With the Excellence folder open in VS Code, access the terminal by clicking the "View" option and choosing "Terminal." Run the start script using the
npm run start
command. The start script will watch for any changes in the code and recompile it.
Event listener for Save button
First, select all the Save buttons on the Lecture Notes page in a NodeList
called saveButtons
. Then we will attach an event listener on them.
constructor(){this.editButtons = document.querySelectorAll(".edit-lecture");this.saveButtons = document.querySelectorAll(".save-lecture");this.events();}
In the events
method, add an event listener which calls the saveLecture
method. Since we have multiple lectures we will attach the callback method to each Save button using a foreach
...