Updating A Blog Post Using The WordPress REST API
This post aims to cover the steps required in order to update a blog post using WordPress's built in REST API. The descriptions provided in this post are specific to the NextJs application created that utilises the REST API, treating WordPress as a headless CMS.
Updating A Post
Users can update a post by clicking the blue update button found on any post that they are the author of. In order to see or use the /blog/update/[id] page the user must be logged in as the author of the post. The page uses the getServerSideProps( ) function to get fetch the blog post and author data.
If an attempt is made to retrieve a blog post that does not exist then the user is provided the /pages/404.tsx page that can be seen in one of the following screenshots. An example of one of these attempts is demonstrated within the following screenshot.
If a blog with the ID provided in the url is found then the data is passed to the page and is then used to auto populate the text area fields with the existing data. Using this approach makes the modification of the page simple as changes to the existing content can be easily made.
By using NextJs dynamic routing the page can easily be accessed by using the correct URL. By using dynamic routing the application can easily read the slug contained within the URL and perform server side rendering based on this data (Vercel and NextJs, n.d.).
The update page created mimics the create page, which can be read about here, however uses a different POST route for the request sent. The request is sent using the fetchJSON function, using a HTTP method of POST directed at the /posts/<id> route of the WordPress REST API. The instructions for updating a post were retrieved from the WordPress developer website (WordPress, n.d.).
The users JSON Web Token is sent within an Authorization header in the format Bearer <token>, as is shown in the following screenshot. More can be read about the applications implementation of authentication and authorization here.
The following screenshot provides an view of the network tab located in the Chrome developer tools, indicating that the update request was successful with an HTTP 200 response.
Conclusion
References
Vercel and NextJs (n.d.). Routing: Dynamic Routes | Next.js. [online] nextjs.org. Available at: https://nextjs.org/docs/routing/dynamic-routes [Accessed 14 Apr. 2021].
WordPress (n.d.). Posts | REST API Handbook. [online] WordPress Developer Resources. Available at: https://developer.wordpress.org/rest-api/reference/posts/#update-a-post [Accessed 18 Apr. 2021].







Comments
Post a Comment