0
0
WordpressHow-ToBeginner · 4 min read

How to Use WordPress as Headless CMS: Simple Guide

To use WordPress as a headless CMS, you manage content in WordPress but deliver it via its REST API or GraphQL to a separate frontend app. This lets you build the frontend with any technology while WordPress handles content storage and editing.
📐

Syntax

Using WordPress as a headless CMS involves fetching content through its API endpoints. The main parts are:

  • WordPress Backend: Manage posts, pages, and media as usual.
  • REST API Endpoint: URLs like https://your-site.com/wp-json/wp/v2/posts provide JSON data.
  • Frontend App: Any framework (React, Vue, Angular) fetches this JSON and renders content.
http/javascript
GET https://your-site.com/wp-json/wp/v2/posts

// Example fetch in JavaScript
fetch('https://your-site.com/wp-json/wp/v2/posts')
  .then(response => response.json())
  .then(posts => console.log(posts));
Output
[ { "id": 1, "date": "2024-06-01T12:00:00", "title": {"rendered": "Hello World"}, "content": {"rendered": "<p>Welcome to WordPress!</p>"} }, ... ]
💻

Example

This example shows a simple React component fetching and displaying WordPress posts using the REST API.

javascript
import React, { useEffect, useState } from 'react';

export default function WordPressPosts() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    async function fetchPosts() {
      const response = await fetch('https://your-site.com/wp-json/wp/v2/posts');
      const data = await response.json();
      setPosts(data);
    }
    fetchPosts();
  }, []);

  return (
    <div>
      <h1>WordPress Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <h2 dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
            <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
          </li>
        ))}
      </ul>
    </div>
  );
}
Output
<h1>WordPress Posts</h1> <ul> <li> <h2>Hello World</h2> <p>Welcome to WordPress!</p> </li> <!-- more posts --> </ul>
⚠️

Common Pitfalls

Common mistakes when using WordPress as a headless CMS include:

  • Not enabling the REST API or using plugins that disable it.
  • Ignoring CORS (Cross-Origin Resource Sharing) issues when fetching data from another domain.
  • Rendering raw HTML without sanitizing, which can cause security risks.
  • Not handling authentication if you need private content.
javascript
/* Wrong: Fetching without handling CORS or errors */
fetch('https://your-site.com/wp-json/wp/v2/posts')
  .then(res => res.json())
  .then(data => console.log(data));

/* Right: Adding error handling and CORS setup on server */
fetch('https://your-site.com/wp-json/wp/v2/posts')
  .then(res => {
    if (!res.ok) throw new Error('Network error');
    return res.json();
  })
  .then(data => console.log(data))
  .catch(err => console.error('Fetch error:', err));
📊

Quick Reference

Summary tips for using WordPress as a headless CMS:

  • Use the built-in REST API at /wp-json/wp/v2/ to get content.
  • Consider GraphQL plugins like WPGraphQL for more flexible queries.
  • Build your frontend with any modern framework fetching JSON data.
  • Handle CORS and authentication if needed.
  • Sanitize HTML content before rendering to keep security.

Key Takeaways

WordPress can serve content via REST API or GraphQL for headless use.
Frontend apps fetch JSON data and render content separately from WordPress backend.
Always handle CORS and sanitize HTML to avoid security issues.
Use authentication for private content access.
Plugins like WPGraphQL offer more query flexibility than REST API.