When reading an article online, I find it helpful to know when the article was last updated. Not all blogs display the last updated value however even when the last updated value is not displayed, the value is accessible via the WordPress REST API.
When viewing a WordPress post, running the following from the browser console
(await (await fetch(
document.querySelector(
'link[rel="alternate"][type="application/json"]'
).href
)).json()).modified
displays the modified
value of the post.
How this Code Works
Get the REST API Route for the Blog Post
The WordPress markup for a blog post includes a <link>
tag in the header that looks similar to
<link
rel="alternate"
type="application/json"
href="https://salferrarello.com/wp-json/wp/v2/posts/6799"
>
where the href
value points to the associated WordPress REST API route for the blog post.
We use document.querySelector() with the selector
link[rel="alternate"][type="application/json"]
to find this DOM element and then we get the .href
value of the element.
Fetch the Response from the Endpoint
Then we call fetch() with the href
value we determined above. Because fetch()
is an asynchronous function, it returns the result wrapped in a Promise so we include the await
keyword.
Note: We could use the Promise .then()
syntax instead but I prefer the more modern use of await
(see Promise and Async / Await).
Decode the Response to an Object
The value returned by fetch()
is a JavaScript Response object. Since the endpoint returns a string that represents an object in JSON format, we can use the .json() method on Response
to get the object. The .json()
method is also asynchronous (and therefore wraps the value in a Promise, so we use a second await
statement).
Extract the Modified Value
At this point, we have a JavaScript object of the information returned by WordPress for this particular blog post. The property we are interested in is .modified
Chrome Browser Extension
Instead of running
(await (await fetch(
document.querySelector(
'link[rel="alternate"][type="application/json"]'
).href
)).json()).modified
from the browser console each time, I’ve wrapped this functionality in a Chrome browser extension, WP Modified.
Leave a Reply