WordPress API

wp rest api

The WordPress REST API is a powerful tool that allows developers to interact with their WordPress site programmatically.

For example, to retrieve a list of posts from this site, you can use the following GET endpoint: https://andrewnjoo.com/wp-json/wp/v2/posts

This URL returns a JSON response containing all the posts on the site. Each post object includes useful information such as the title, content, and date:

[
  {
    "id": 656,
    "date": "2024-06-03T06:52:58",
    "date_gmt": "2024-06-03T06:52:58",
    "guid": {
      "rendered": "https://andrewnjoo.com/?p=656"
    },
    "modified": "2024-06-03T07:00:19",
    "modified_gmt": "2024-06-03T07:00:19",
    "slug": "wordpress-api",
    "status": "publish",
    "type": "post",
    "link": "https://andrewnjoo.com/wordpress-api/",
    "title": {
      "rendered": "WordPress API"
    },
    "content": {
      "rendered": "<p>The WordPress <a href=\"https://developer.wordpress.org/rest-api/\">REST API</a> is a powerful tool ...</p>"
    }
  },
...
]

To get the next page of posts just add the argument e.g. ?page=2 to the end of your query.

In addition to the post data, the total number of posts is returned in the response headers under X-WP-Total. This is useful for paginating through posts:

To do a quick check you can e.g. make a GET request using your browser URL bar e.g. https://www.andrewnjoo.com/wp-json/wp/v2/posts?per_page=1, and check the X-WP-Total header in the response.1

To interact with the API, you can use tools like cURL, Postman, or even JavaScript’s fetch function. Here’s an example using cURL to get the HTTP headers including total number of posts:

> curl -I https://andrewnjoo.com/wp-json/wp/v2/posts

...

X-WP-Total: 23
X-WP-TotalPages: 3

Additionally, the API supports authentication, allowing you to manage your site securely.

Embrace the WordPress REST API to enhance your site’s functionality and integrate it with external applications seamlessly. Happy coding!

  1. StackOverflow β†©οΈŽ

Leave a Reply

Your email address will not be published. Required fields are marked *