🚀 WordPress as Content API
WordPress theme limiting you? Build React/Vue frontend, use WordPress as content source. REST API turns WordPress into headless CMS.
Built-in Endpoints
# All built-in, no setup needed! # Get all posts GET https://yoursite.com/wp-json/wp/v2/posts # Get single post GET https://yoursite.com/wp-json/wp/v2/posts/123 # Get pages GET https://yoursite.com/wp-json/wp/v2/pages # Get categories GET https://yoursite.com/wp-json/wp/v2/categories # Get tags GET https://yoursite.com/wp-json/wp/v2/tags # Get media GET https://yoursite.com/wp-json/wp/v2/media # Get users GET https://yoursite.com/wp-json/wp/v2/users
🎯 Fetch Posts with JavaScript
// Fetch latest posts
async function getPosts() {
const response = await fetch('https://yoursite.com/wp-json/wp/v2/posts?per_page=10');
const posts = await response.json();
posts.forEach(post => {
console.log(post.title.rendered);
console.log(post.excerpt.rendered);
console.log(post.link);
});
}
// With filters
const response = await fetch(
'https://yoursite.com/wp-json/wp/v2/posts?' +
'categories=5&' +
'per_page=5&' +
'orderby=date&' +
'order=desc'
);
// Search posts
const searchResponse = await fetch(
'https://yoursite.com/wp-json/wp/v2/posts?search=react'
);
React Example: Blog Feed
import { useEffect, useState } from 'react';
function BlogFeed() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchPosts() {
try {
const response = await fetch(
'https://yoursite.com/wp-json/wp/v2/posts?_embed'
);
const data = await response.json();
setPosts(data);
} catch (error) {
console.error('Error fetching posts:', error);
} finally {
setLoading(false);
}
}
fetchPosts();
}, []);
if (loading) return Loading...;
return (
{posts.map(post => (
{post.title.rendered}
{/* Featured image via _embed */}
{post._embedded?.['wp:featuredmedia']?.[0] && (
)}
Read More
))}
);
}
Custom Endpoints
// functions.php - Create custom endpoint
add_action('rest_api_init', function() {
register_rest_route('myplugin/v1', '/popular-posts', array(
'methods' => 'GET',
'callback' => 'get_popular_posts',
'permission_callback' => '__return_true'
));
});
function get_popular_posts($request) {
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
$posts = get_posts($args);
$data = array();
foreach ($posts as $post) {
$data[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'views' => get_post_meta($post->ID, 'views', true),
'link' => get_permalink($post->ID)
);
}
return rest_ensure_response($data);
}
// Access: GET /wp-json/myplugin/v1/popular-posts
Authentication
🔐 JWT Authentication
// Install JWT plugin: jwt-authentication-for-wp-rest-api
// Login to get token
const loginResponse = await fetch('https://yoursite.com/wp-json/jwt-auth/v1/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: 'admin',
password: 'password123'
})
});
const { token } = await loginResponse.json();
// Use token for authenticated requests
const createPost = await fetch('https://yoursite.com/wp-json/wp/v2/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
title: 'New Post via API',
content: 'Post content here',
status: 'publish'
})
});
✅ Use Cases
- Next.js blog: WordPress backend, React frontend
- Mobile apps: iOS/Android apps consuming WordPress content
- Multi-platform: Same content on web, mobile, Apple TV
- Microservices: WordPress as content service in architecture
- Static site generators: Gatsby, Hugo pulling from WordPress
💡 Performance Tips
- Use _embed: Get featured images, author in one request
- Limit fields:
?_fields=id,title,excerptfor faster responses - Enable caching: Use Redis/Varnish for API responses
- Pagination: Don’t fetch all posts at once
- CDN: Cache JSON responses on CDN edge
🎯 Query Parameters Cheat Sheet
| Parameter | Example |
|---|---|
per_page |
?per_page=10 |
page |
?page=2 |
search |
?search=wordpress |
categories |
?categories=5,8 |
orderby |
?orderby=date |
_embed |
?_embed |
“Migrated blog to Next.js frontend with WordPress REST API backend. SEO improved (server-side rendering), load time halved, infinite design freedom. WordPress admin for content, React for UI. Best of both worlds.”
