How to Get Posts Using REST API in WordPress
To get posts using the WordPress REST API, send a GET request to
/wp-json/wp/v2/posts. This endpoint returns a list of posts in JSON format, which you can filter or paginate using query parameters.Syntax
The basic syntax to get posts via the WordPress REST API is:
GET /wp-json/wp/v2/posts: Fetches all posts.- Query parameters can be added to filter results, such as
?per_page=5to limit posts per page. - Use
?page=2to get the second page of posts.
http
GET https://example.com/wp-json/wp/v2/posts # Optional query parameters: # ?per_page=5 - number of posts per page # &page=2 - page number # &categories=3 - filter posts by category ID
Example
This example fetches the first 3 posts from a WordPress site using the REST API and shows the JSON response structure.
javascript
fetch('https://example.com/wp-json/wp/v2/posts?per_page=3') .then(response => response.json()) .then(posts => { posts.forEach(post => { console.log('Title:', post.title.rendered); console.log('Date:', post.date); console.log('Link:', post.link); console.log('---'); }); }) .catch(error => console.error('Error fetching posts:', error));
Output
Title: Hello World
Date: 2024-06-01T12:00:00
Link: https://example.com/hello-world
---
Title: Sample Post
Date: 2024-05-28T09:30:00
Link: https://example.com/sample-post
---
Title: Another Post
Date: 2024-05-20T15:45:00
Link: https://example.com/another-post
---
Common Pitfalls
- Not using the full URL including
/wp-json/wp/v2/postswill cause errors. - Ignoring pagination can lead to incomplete data if many posts exist.
- Trying to access private or draft posts without authentication will return empty results.
- Incorrectly formatting query parameters (e.g., missing
?or using wrong keys) will cause the API to ignore filters.
javascript
/* Wrong way: Missing /wp-json/wp/v2/posts */ fetch('https://example.com/posts') .then(res => res.json()) .catch(err => console.error('Error:', err)); /* Right way: Full REST API endpoint */ fetch('https://example.com/wp-json/wp/v2/posts') .then(res => res.json()) .then(data => console.log(data));
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| per_page | Number of posts per page (max 100) | ?per_page=5 |
| page | Page number for pagination | ?page=2 |
| categories | Filter posts by category ID | ?categories=3 |
| search | Search posts by keyword | ?search=wordpress |
| orderby | Sort posts by field (date, title) | ?orderby=date |
Key Takeaways
Use the endpoint /wp-json/wp/v2/posts to fetch posts via REST API.
Add query parameters like per_page and page to control results and pagination.
Ensure the URL is complete and correct to avoid errors.
Private or draft posts require authentication to access.
Use fetch or any HTTP client to get and handle the JSON response.