Home / CMS & DEV / WordPress REST API
CMS & DEV
Consume WordPress REST API from React
WordPress natively exposes a REST API to /wp-json/wp/v2/. Here's how to recover your items cleanly from a React application, without additional plugin.
Retrieve Items with Fetch
import { useEffect, useState } from 'react';
function ArticlesList() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://monsite.com/wp-json/wp/v2/posts?_embed')
.then((res) => res.json())
.then((data) => setPosts(data));
}, []);
return (
{posts.map((post) => (
- {post.title.rendered}
))}
);
}
Activate Cors on the WordPress side
add_action('rest_api_init', function () {
header('Access-Control-Allow-Origin: https://monapp-react.com');
header('Access-Control-Allow-Methods: GET');
});
Tip: Use _embed in the URL to retrieve the highlighted image and the author in a single query, instead of multiplying API calls.
frequently asked questions
Do you need a plugin to activate the REST API?
No, it is enabled by default since WordPress 4.7 without additional installation.
How to post content and not just read it?
You must then authenticate via Application Passwords or JWT and send authenticated POST requests.