One of the quirks of the WordPress REST API is how it handles not found errors. WordPress would love if every request made to the API used ID’s when referencing posts, categories, pages and so on. Why? Well because every item in WordPress has a unique ID so there’s no possibility of confusion.
The trouble for people making single page apps, is we typically want the URL that the user sees to use words and not numbers. We want it to look like:
https://yoursite.com/about
and not like:
https://yoursite.com/page/238
As a way to accommodate that, the REST API will let you add a parameter to your URL for the slug of your page/post. That’s great because we can use the parameter from our browser’s URL to tell our app, which page/post to pull from the API. They match. Win for SEO and usability.
The only trouble is in how WordPress handles not found errors. When you make a request to the API using an ID that doesn’t exist, you end up with a response that looks like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"code": "rest_post_invalid_id", | |
"message": "Invalid post ID.", | |
"data": { | |
"status": 404 | |
} | |
} |
which is fantastic. But if you make a request for an item using a slug that doesn’t exist, you’ll get this in response:
[ ]
It’s just an empty array with no error message at all. Why it’s like this, I don’t know, but it is possible to still work with it. Here’s what I’ve done in Vue apps for this.
I make a request using Axios based on the URL slug via the REST API. Before I assign the response, I check to see if the response is empty or not. If it is empty I programmatically tell the router to go to /not-found. I created a page inside my WordPress admin called Not Found just for such an occasion. Here’s what the first part of that function looks like:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
HTTP.get('wp-json/wp/v2/pages?slug=' + this.$route.params.id) | |
.then(resp => { | |
if (resp.data == '') { | |
this.$router.push('/not-found'); | |
} | |
… |
Simple right? Handling pages that don’t exist is an import consideration for any site. WordPress has taken care of this for us when using PHP rendered themes, but for sites running as single page apps, we have to remember to account for this ourselves. You can apply this method to Angular, React or whatever your personal preference is.
Leave a Reply