The WordPress REST API transformed WordPress from a traditional CMS into a flexible content platform capable of powering mobile apps, JavaScript frontends, static site generators, and complex application architectures.
Since WordPress 4.7 (2016), the REST API has been part of WordPress core — providing programmatic access to posts, pages, users, taxonomies, settings, and any custom data through standard HTTP endpoints.
This guide covers everything you need to start building with the WordPress REST API — from reading public data to authenticated writes, custom endpoints, and security best practices.
A REST API (Representational State Transfer Application Programming Interface) is a way to interact with a web application over HTTP using standard methods — GET, POST, PUT/PATCH, and DELETE.
WordPress's REST API exposes your WordPress data as JSON at https://yourdomain.com/wp-json/wp/v2/. Any application that can make HTTP requests can interact with your WordPress site through this interface.
What the REST API enables:
WordPress provides REST API endpoints for all built-in content types. Open this URL in your browser (on any WordPress site):
GET https://yourdomain.com/wp-json/wp/v2/posts
You'll see a JSON array of your published posts with their IDs, titles, content, author, categories, and more.
Default available routes:
| Content Type | Route |
|---|---|
| Posts | /wp-json/wp/v2/posts |
| Pages | /wp-json/wp/v2/pages |
| Media | /wp-json/wp/v2/media |
| Categories | /wp-json/wp/v2/categories |
| Tags | /wp-json/wp/v2/tags |
| Users | /wp-json/wp/v2/users |
| Comments | /wp-json/wp/v2/comments |
| Custom Post Types | /wp-json/wp/v2/{post-type-slug} |
GET /wp-json/ returns all available routes and their supported methods — a complete API map.GET requests don't require authentication for public content.
Fetch All Posts:
fetch('https://yourdomain.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(posts => {
posts.forEach(post => {
console.log(post.title.rendered, post.link);
});
});
Fetch a Single Post by ID:
fetch('https://yourdomain.com/wp-json/wp/v2/posts/42')
.then(response => response.json())
.then(post => console.log(post));
Query Parameters:
// Get posts in category ID 5
GET /wp-json/wp/v2/posts?categories=5
// Get posts with tag ID 8
GET /wp-json/wp/v2/posts?tags=8
// Search posts
GET /wp-json/wp/v2/posts?search=wordpress+tutorial
// Limit fields returned (reduces response size)
GET /wp-json/wp/v2/posts?_fields=id,title,excerpt,link
// Pagination
GET /wp-json/wp/v2/posts?page=2&per_page=10
// Order results
GET /wp-json/wp/v2/posts?orderby=title&order=asc
Get Total Post Count from Response Headers:
fetch('https://yourdomain.com/wp-json/wp/v2/posts?per_page=10')
.then(response => {
const totalPosts = response.headers.get('X-WP-Total');
const totalPages = response.headers.get('X-WP-TotalPages');
console.log(`${totalPosts} posts across ${totalPages} pages`);
return response.json();
})
.then(posts => console.log(posts));
Public data (published posts, pages, categories) requires no authentication. For creating, updating, deleting content, or accessing private data — authentication is required.
Method 1: Application Passwords (Built In — WordPress 5.6+)
Application Passwords are WordPress's built-in REST API authentication system. No plugins required.
const username = 'your_username';
const appPassword = 'xxxx xxxx xxxx xxxx xxxx xxxx';
const headers = {
'Authorization': 'Basic ' + btoa(username + ':' + appPassword.replace(/\s/g, '')),
'Content-Type': 'application/json'
};
// Create a new post
fetch('https://yourdomain.com/wp-json/wp/v2/posts', {
method: 'POST',
headers: headers,
body: JSON.stringify({
title: 'New Post via REST API',
content: 'This post was created through the REST API.',
status: 'publish'
})
})
.then(response => response.json())
.then(post => console.log('Created post:', post.id));
Method 2: Cookie Authentication (For Admin AJAX)
For JavaScript running within the WordPress admin context, WordPress automatically authenticates via cookies. Use wp.apiFetch:
// In admin context, wp.apiFetch handles auth automatically
wp.apiFetch({
path: '/wp/v2/posts',
method: 'POST',
data: {
title: 'New Post',
status: 'draft'
}
}).then(post => console.log(post));
Method 3: OAuth (JWT Tokens — Via Plugin)
For public-facing applications where users authenticate as themselves, install JWT Authentication for WP REST API plugin:
// Authenticate and get token
const authResponse = await fetch('https://yourdomain.com/wp-json/jwt-auth/v1/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'user', password: 'pass' })
});
const { token } = await authResponse.json();
// Use token for subsequent requests
fetch('https://yourdomain.com/wp-json/wp/v2/posts', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
Create a Post:
const response = await fetch('https://yourdomain.com/wp-json/wp/v2/posts', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa('username:app_password'),
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'My API Post',
content: 'Post content goes here.
',
status: 'publish', // publish, draft, private
categories: [3, 7], // Array of category IDs
tags: [12], // Array of tag IDs
featured_media: 45, // Featured image attachment ID
excerpt: 'Post excerpt.',
slug: 'my-api-post'
})
});
const newPost = await response.json();
console.log('New post ID:', newPost.id);
Update a Post:
fetch('https://yourdomain.com/wp-json/wp/v2/posts/42', {
method: 'POST', // WordPress REST API uses POST for updates
headers: { /* auth headers */ },
body: JSON.stringify({
title: 'Updated Title',
status: 'draft'
})
});
Delete a Post:
// Move to trash
fetch('https://yourdomain.com/wp-json/wp/v2/posts/42', {
method: 'DELETE',
headers: { /* auth headers */ }
});
// Force delete (bypass trash)
fetch('https://yourdomain.com/wp-json/wp/v2/posts/42?force=true', {
method: 'DELETE',
headers: { /* auth headers */ }
});
Extend the API with your own endpoints — for custom functionality, computed data, or custom post type interactions.
add_action( 'rest_api_init', function() {
register_rest_route(
'myplugin/v1', // Namespace
'/featured-posts', // Route
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'myplugin_get_featured_posts',
'permission_callback' => '__return_true',
'args' => array(
'limit' => array(
'default' => 5,
'sanitize_callback' => 'absint',
'validate_callback' => function( $value ) {
return $value > 0 && $value <= 50;
}
)
)
)
);
});
function myplugin_get_featured_posts( WP_REST_Request $request ) {
$limit = $request->get_param( 'limit' );
$posts = get_posts( array(
'post_type' => 'post',
'posts_per_page' => $limit,
'meta_key' => 'is_featured',
'meta_value' => '1',
) );
if ( empty( $posts ) ) {
return new WP_Error(
'no_featured_posts',
'No featured posts found',
array( 'status' => 404 )
);
}
$data = array_map( function( $post ) {
return array(
'id' => $post->ID,
'title' => get_the_title( $post ),
'excerpt' => get_the_excerpt( $post ),
'link' => get_permalink( $post ),
'image' => get_the_post_thumbnail_url( $post, 'large' ),
);
}, $posts );
return new WP_REST_Response( $data, 200 );
}
Access this endpoint at: GET https://yourdomain.com/wp-json/myplugin/v1/featured-posts?limit=3
Permission Callback Options:
// Public — anyone can access
'permission_callback' => '__return_true',
// Logged in users only
'permission_callback' => function() {
return is_user_logged_in();
},
// Editors and above
'permission_callback' => function() {
return current_user_can( 'edit_posts' );
},
// Custom capability check
'permission_callback' => function() {
return current_user_can( 'manage_options' );
},
Expose custom fields (post meta) in the REST API using register_rest_field():
add_action( 'rest_api_init', function() {
register_rest_field(
'post', // Object type
'reading_time', // Field name in API response
array(
'get_callback' => function( $post_data ) {
$content = get_post_field( 'post_content', $post_data['id'] );
$word_count = str_word_count( strip_tags( $content ) );
return ceil( $word_count / 200 ) . ' min read';
},
'schema' => array(
'type' => 'string',
'description' => 'Estimated reading time',
),
)
);
});
Now every post in the REST API response includes "reading_time": "5 min read".
Always validate and sanitise input:
'args' => array(
'search_term' => array(
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => function( $value ) {
return is_string( $value ) && strlen( $value ) <= 100;
}
)
)
Return proper HTTP status codes:
| Status Code | Meaning |
|---|---|
200 | Success |
201 | Resource created |
400 | Bad request (invalid input) |
401 | Unauthorised (not authenticated) |
403 | Forbidden (authenticated but not permitted) |
404 | Not found |
500 | Server error |
Rate limiting: For public endpoints, implement rate limiting to prevent abuse:
$rate_limit_key = 'api_limit_' . $_SERVER['REMOTE_ADDR'];
$requests = get_transient( $rate_limit_key ) ?: 0;
if ( $requests > 60 ) { // 60 requests per minute
return new WP_Error( 'rate_limit', 'Too many requests', array( 'status' => 429 ) );
}
set_transient( $rate_limit_key, $requests + 1, 60 );
Add to your functions.php:
add_filter( 'rest_authentication_errors', function( $result ) {
if ( ! is_user_logged_in() ) {
return new WP_Error( 'rest_not_logged_in', 'API restricted to authenticated users.', array( 'status' => 401 ) );
}
return $result;
});
Note: This blocks legitimate uses like site embeds. Consider disabling only specific endpoints rather than all access.
useEffect and fetch, manage state with useState or Redux, and render posts as React components. The Next.js WordPress starter is a popular production-ready setup.
curl https://yourdomain.com/wp-json/wp/v2/posts
The WordPress REST API is one of the most powerful features in modern WordPress — it transforms the CMS from a traditional PHP-rendered website engine into a flexible content platform.
Whether you're building a headless frontend, a mobile app, or a complex plugin, the REST API provides the foundation. Master GET requests first, then authentication, then custom endpoints.
Contact us for custom WordPress REST API development