WordPress REST API Basics: What Can You Do With `/wp-json/`?
Parts of WordPress that look like they're reading straight from the database are often actually going through an HTTP API behind the scenes. Loading a post list dynamically with JavaScript, or having an external PHP script pull "just the titles and excerpts of the latest three posts" — both of these can be done without touching SQL directly, by calling the REST API that ships with WordPress…
WordPress includes a built-in REST API since version 4.7, which allows systems outside of WordPress to interact with its content without direct database access. By appending `/wp-json/` to a site's URL, you can view a list of available endpoints in JSON format. The most commonly used endpoint, `/wp-json/wp/v2/posts`, returns published posts as a JSON array, including details like post ID, title, content, excerpt, publish date, and permalink.
Query parameters can be added to control the number of results, page number, and filtering options. However, certain actions like fetching drafts or creating/updating posts require authentication. The `_embed` parameter can be used to reduce multiple requests by embedding related data, such as featured images and categories, directly into the response.
A practical example of using WordPress's REST API is seen in the landing page block for "latest posts" on the JP and EN sites. This block retrieves the latest posts by making a single HTTP request to the site's WordPress instance. The response is then parsed to extract relevant information, such as title, excerpt, permalink, featured image URL, and category name, and formatted into HTML. This approach abstracts away the underlying database structure, allowing integration based on a stable JSON interface.
To prevent overloading the server with requests on each page load, the function caches the result as a JSON file for one hour. If the request fails or the cache is stale, it gracefully serves the last successful cache or an empty array if no cache exists, ensuring no broken sections are displayed. Authentication is mandatory for endpoints that modify content, utilizing WordPress's nonce system or Application Passwords for external applications.
This structured approach ensures efficient, secure, and stable interaction with WordPress content via its REST API.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.