惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Cisco Blogs
Schneier on Security
Schneier on Security
T
Tor Project blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tenable Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
Scott Helme
Scott Helme
Webroot Blog
Webroot Blog
Project Zero
Project Zero
Google Online Security Blog
Google Online Security Blog
The Last Watchdog
The Last Watchdog
Spread Privacy
Spread Privacy
Hacker News: Ask HN
Hacker News: Ask HN
PCI Perspectives
PCI Perspectives
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
W
WeLiveSecurity
Attack and Defense Labs
Attack and Defense Labs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
N
News | PayPal Newsroom
Help Net Security
Help Net Security
The Hacker News
The Hacker News
H
Heimdal Security Blog
O
OpenAI News
S
Security @ Cisco Blogs
N
News and Events Feed by Topic
Cyberwarzone
Cyberwarzone
Simon Willison's Weblog
Simon Willison's Weblog
G
GRAHAM CLULEY
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园 - 叶小钗
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
A
Arctic Wolf
I
Intezer
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Security Affairs
P
Proofpoint News Feed
S
Secure Thoughts
腾讯CDC
Google DeepMind News
Google DeepMind News
量子位
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
WordPress Is Not Dead — It's Headless: A Complete React Integration Guide
Kushang Tail · 2026-05-13 · via DEV Community

"Your content layer and your presentation layer don't have to be married anymore — and that divorce might be the best thing that ever happened to your project."

If you've been in web development for a while, you've probably heard the buzz around headless CMS. But what does it actually mean? Is it just another trend, or is it solving real problems that developers face every day?

In this guide, we'll walk through everything — from the concept of headless CMS, why WordPress is still a powerhouse even in this modern setup, and how React fits in as the perfect frontend companion. By the end, you'll not only understand the why, but also the how — with real code, real comparisons, and real use cases.

Let's cut the head off. 🪓


📚 Table of Contents

  1. What Is a Headless CMS?
  2. Types of Headless CMS
  3. Real Use Cases of Headless CMS
  4. WordPress vs. Other Headless CMS Platforms
  5. What Is React — and Why Does It Fit Here?
  6. Setting Up WordPress as a Headless CMS
  7. Consuming WordPress API in React
  8. Traditional WordPress vs. Headless WordPress — Deep Comparison
  9. 4 Real-World Use Cases with Architecture
  10. Final Thoughts

1. What Is a Headless CMS?

A traditional CMS — like classic WordPress — is a coupled system. The backend (where you manage content) and the frontend (where your users see it) are tightly bound together. WordPress serves both the admin panel and the rendered HTML pages in one monolith.

A headless CMS decouples this. The CMS handles only one thing: managing and delivering content via an API. The "head" — the presentation layer — is completely removed. You choose whatever frontend technology you want: React, Vue, Next.js, a mobile app, a smart TV app, a voice assistant — anything that can consume an API.

Traditional CMS:
[ Content Management ] → [ Template Engine ] → [ HTML to Browser ]

Headless CMS:
[ Content Management ] → [ REST API / GraphQL ] → [ Your Frontend of Choice ]

Enter fullscreen mode Exit fullscreen mode

Why Does This Matter?

Pain Point (Traditional) How Headless Solves It
Frontend locked to PHP templates Use any JS framework
Tight coupling slows deployments Frontend/backend deploy independently
Scaling the whole app is expensive Scale only what's needed
Hard to support multiple channels One API feeds web, mobile, IoT
Security vulnerabilities at the frontend Frontend has no direct DB access

2. Types of Headless CMS

Not all headless CMS platforms are built the same. Here's a breakdown of the major categories:

🔹 API-First CMS (Purpose-Built Headless)

Built from the ground up to serve content via API. No legacy frontend baggage.

Examples: Contentful, Sanity, Strapi, Hygraph (GraphCMS)

Best for: Greenfield projects, developer-first teams, omnichannel content

🔹 Traditional CMS Gone Headless (Decoupled)

Full-featured CMS systems with headless capabilities bolted on — like WordPress with the REST API or WPGraphQL.

Examples: WordPress, Drupal, Joomla

Best for: Existing WordPress teams, content-heavy sites, organizations already invested in WordPress

🔹 Git-Based Headless CMS

Content is stored in a Git repository as Markdown or JSON files. The CMS is just an editor that commits to Git.

Examples: Netlify CMS (Decap), Forestry, TinaCMS

Best for: JAMstack projects, developer-managed content, static sites

🔹 SaaS Commerce Headless CMS

Specialized headless platforms for e-commerce, where product data is the content.

Examples: Shopify Storefront API, BigCommerce, Swell

Best for: E-commerce brands needing custom UX with powerful commerce backends


3. Real Use Cases of Headless CMS

Wondering if headless is "production-ready"? Here are real-world adoption stories:

  • Nike uses a headless architecture to power their product pages across web, mobile, and in-store kiosks from a single content source.
  • Spotify decoupled their editorial blog from their core app infrastructure, enabling faster content updates without touching the core product.
  • Harley-Davidson migrated to a headless setup and reported a ~400% increase in organic traffic and significantly faster page loads.
  • The New Yorker uses a decoupled WordPress to manage editorial content while serving it via a custom React frontend — allowing editors to work in a familiar CMS while engineers innovate on the frontend freely.

4. WordPress vs. Other Headless CMS Platforms

Here's the big question — why WordPress for headless, when purpose-built headless platforms exist?

📊 Full Comparison Table

Feature WordPress (Headless) Contentful Sanity Strapi Hygraph
Open Source ✅ Yes ❌ No ✅ (Studio) ✅ Yes ❌ No
Self-hosted ✅ Yes ❌ Cloud only ✅ (Studio) ✅ Yes ❌ Cloud only
API Type REST + GraphQL* REST + GraphQL GROQ + GraphQL REST + GraphQL GraphQL only
Free Tier ✅ Fully free ⚠️ Limited ⚠️ Limited ✅ Free (self-hosted) ⚠️ Limited
Editor Experience ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐
Plugin Ecosystem 60,000+ plugins ❌ Minimal ❌ Minimal ⚠️ Growing ❌ Minimal
Community Size 🌍 Massive Medium Medium Growing Small
Learning Curve Low (editors) Medium Medium-High Medium Medium
Content Modeling Good (CPTs + ACF) Excellent Excellent Good Excellent
Media Management ✅ Built-in ✅ Built-in ✅ Built-in ✅ Built-in ✅ Built-in
Multi-language ✅ (WPML plugin) ✅ Native ✅ Native ⚠️ Plugin ✅ Native
Pricing Free (hosting cost) $300+/mo (scale) Pay-as-you-go Free / $$$ $299+/mo (scale)

*GraphQL via WPGraphQL plugin (500k+ active installs)

📈 Market Share Reality Check

  • WordPress powers 43.5% of all websites on the internet (W3Techs)
  • 65.3% market share among CMS platforms
  • Over 810 million websites use WordPress
  • The WordPress REST API has been built-in since WordPress 4.7 (2016)

The bottom line: If your team already knows WordPress, your editors love the Gutenberg experience, or you want a proven, free, self-hosted solution — WordPress headless is an incredibly powerful choice. Purpose-built headless CMS platforms win on developer experience for greenfield projects, but WordPress wins on cost, ecosystem, and editor familiarity.


5. What Is React — and Is It the Best Choice?

React is a JavaScript library for building user interfaces, developed and maintained by Meta. It's component-based, which means you build UIs out of small, reusable pieces, each managing their own state.

// A simple React component
function ArticleCard({ title, excerpt, date }) {
  return (
    <article className="card">
      <h2>{title}</h2>
      <p>{excerpt}</p>
      <time>{date}</time>
    </article>
  );
}

Enter fullscreen mode Exit fullscreen mode

Why React Is an Excellent Choice for WordPress Headless

Reason Detail
Component reusability Build once, reuse across pages
Rich ecosystem Next.js, Gatsby, React Query, Zustand
Performance Virtual DOM, code-splitting, lazy loading
Community Largest frontend community (Stack Overflow 2024: most used framework)
ISR / SSG / SSR Via Next.js — perfect for SEO + speed
TypeScript support First-class TS integration

React vs. Vue vs. Svelte for Headless WordPress

React Vue Svelte
Popularity 🥇 40.6% 🥈 18.5% 🥉 6.5%
SSR Framework Next.js Nuxt.js SvelteKit
WordPress integrations Most (WPGraphQL + Apollo, etc.) Good Limited
Learning curve Medium Easy Easy
Job market Largest Good Niche

(Source: Stack Overflow Developer Survey 2024)

Verdict: React, especially paired with Next.js, is the most battle-tested, ecosystem-rich, and job-market-relevant choice for a WordPress headless setup.


6. Setting Up WordPress as a Headless CMS

Let's get our hands dirty. Here's a step-by-step overview of the setup.

Step 1: Install WordPress

You can use a local environment (LocalWP, XAMPP, Lando) or a cloud server. For headless use, you only need the WordPress admin — no theme rendering required.

# Using WP-CLI
wp core download
wp config create --dbname=headless_wp --dbuser=root --dbpass=password
wp core install --url=http://localhost --title="Headless WP" \
  --admin_user=admin --admin_password=secret --admin_email=admin@example.com

Enter fullscreen mode Exit fullscreen mode

Step 2: Disable the Frontend (Optional but Recommended)

Since WordPress won't render pages, you can disable frontend access with a simple plugin or functions.php tweak:

<?php
/**
 * Redirect all frontend requests to the admin.
 * Only use this if WordPress is purely API-driven.
 */
add_action( 'template_redirect', 'redirect_frontend_to_admin' );

function redirect_frontend_to_admin(): void {
    if ( ! is_admin() && ! ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
        wp_safe_redirect( admin_url() );
        exit;
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Enable and Test the REST API

WordPress REST API is enabled by default. Test it:

# List all posts
curl http://yourdomain.com/wp-json/wp/v2/posts

# Get a single post by ID
curl http://yourdomain.com/wp-json/wp/v2/posts/1

# Get custom post types (if registered)
curl http://yourdomain.com/wp-json/wp/v2/projects

Enter fullscreen mode Exit fullscreen mode

Step 4: Install WPGraphQL (Recommended for React)

For more flexible queries, install the WPGraphQL plugin — it gives you a powerful GraphQL endpoint.

Plugin: WPGraphQL
Install: Plugins → Add New → Search "WPGraphQL" → Install & Activate
GraphQL Endpoint: http://yourdomain.com/graphql

Enter fullscreen mode Exit fullscreen mode

Step 5: Configure CORS

Your React app (running on localhost:3000 or a different domain) needs to communicate with WordPress. Add CORS headers:

<?php
/**
 * Add CORS headers for the REST API and GraphQL.
 *
 * @param WP_HTTP_Response $response The response object.
 * @return WP_HTTP_Response
 */
add_filter( 'rest_pre_serve_request', 'set_cors_headers_for_rest_api', 10, 1 );

function set_cors_headers_for_rest_api( WP_HTTP_Response $response ): WP_HTTP_Response {
    $allowed_origins = array(
        'http://localhost:3000',
        'https://yourreactapp.com',
    );

    $origin = isset( $_SERVER['HTTP_ORIGIN'] ) 
        ? sanitize_url( wp_unslash( $_SERVER['HTTP_ORIGIN'] ) ) 
        : '';

    if ( in_array( $origin, $allowed_origins, true ) ) {
        $response->header( 'Access-Control-Allow-Origin', $origin );
        $response->header( 'Access-Control-Allow-Methods', 'GET, POST, OPTIONS' );
        $response->header( 'Access-Control-Allow-Credentials', 'true' );
    }

    return $response;
}

Enter fullscreen mode Exit fullscreen mode

Step 6: Register Custom Post Types with REST API Support

<?php
/**
 * Register a Projects custom post type with REST API support.
 */
add_action( 'init', 'register_projects_post_type' );

function register_projects_post_type(): void {
    $labels = array(
        'name'          => __( 'Projects', 'your-textdomain' ),
        'singular_name' => __( 'Project', 'your-textdomain' ),
    );

    $args = array(
        'labels'       => $labels,
        'public'       => true,
        'show_in_rest' => true,       // 👈 This enables REST API support
        'rest_base'    => 'projects', // 👈 API endpoint: /wp-json/wp/v2/projects
        'supports'     => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
    );

    register_post_type( 'project', $args );
}

Enter fullscreen mode Exit fullscreen mode


7. Consuming the WordPress API in React

Now the fun part — the React side.

Setting Up Next.js Project

npx create-next-app@latest wp-headless --typescript
cd wp-headless
npm install @apollo/client graphql  # if using GraphQL
# or just use fetch for REST API

Enter fullscreen mode Exit fullscreen mode

Environment Variables

# .env.local
NEXT_PUBLIC_WP_API_URL=http://your-wordpress-site.com/wp-json/wp/v2
NEXT_PUBLIC_WP_GRAPHQL_URL=http://your-wordpress-site.com/graphql

Enter fullscreen mode Exit fullscreen mode

Fetching Posts via REST API

// lib/wordpress.ts
const WP_API = process.env.NEXT_PUBLIC_WP_API_URL;

export interface WPPost {
  id: number;
  slug: string;
  title: { rendered: string };
  excerpt: { rendered: string };
  content: { rendered: string };
  date: string;
  _embedded?: {
    'wp:featuredmedia'?: Array<{ source_url: string; alt_text: string }>;
  };
}

export async function getAllPosts(): Promise<WPPost[]> {
  const res = await fetch(
    `${WP_API}/posts?_embed&per_page=12`,
    { next: { revalidate: 60 } } // ISR: revalidate every 60 seconds
  );

  if (!res.ok) {
    throw new Error(`Failed to fetch posts: ${res.status}`);
  }

  return res.json();
}

export async function getPostBySlug(slug: string): Promise<WPPost> {
  const res = await fetch(
    `${WP_API}/posts?slug=${slug}&_embed`,
    { next: { revalidate: 60 } }
  );

  if (!res.ok) {
    throw new Error(`Failed to fetch post: ${res.status}`);
  }

  const posts: WPPost[] = await res.json();
  return posts[0];
}

Enter fullscreen mode Exit fullscreen mode

Blog Index Page (Next.js App Router)

// app/blog/page.tsx
import { getAllPosts, WPPost } from '@/lib/wordpress';
import PostCard from '@/components/PostCard';

export const metadata = {
  title: 'Blog | My Headless WordPress Site',
};

export default async function BlogPage() {
  const posts = await getAllPosts();

  return (
    <main className="container mx-auto px-4 py-12">
      <h1 className="text-4xl font-bold mb-8">Latest Articles</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {posts.map((post: WPPost) => (
          <PostCard key={post.id} post={post} />
        ))}
      </div>
    </main>
  );
}

Enter fullscreen mode Exit fullscreen mode

Post Card Component

// components/PostCard.tsx
import Link from 'next/link';
import Image from 'next/image';
import { WPPost } from '@/lib/wordpress';

interface PostCardProps {
  post: WPPost;
}

export default function PostCard({ post }: PostCardProps) {
  const featuredImage = post._embedded?.['wp:featuredmedia']?.[0];
  const title = post.title.rendered;
  const excerpt = post.excerpt.rendered.replace(/<[^>]*>/g, '');
  const date = new Date(post.date).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });

  return (
    <article className="rounded-xl overflow-hidden border border-gray-200 hover:shadow-lg transition-shadow">
      {featuredImage && (
        <Image
          src={featuredImage.source_url}
          alt={featuredImage.alt_text || title}
          width={600}
          height={340}
          className="w-full object-cover"
        />
      )}
      <div className="p-5">
        <time className="text-sm text-gray-500">{date}</time>
        <h2 className="text-xl font-semibold mt-2 mb-3">{title}</h2>
        <p className="text-gray-600 text-sm line-clamp-3">{excerpt}</p>
        <Link
          href={`/blog/${post.slug}`}
          className="inline-block mt-4 text-blue-600 font-medium hover:underline"
        >
          Read More →
        </Link>
      </div>
    </article>
  );
}

Enter fullscreen mode Exit fullscreen mode

Single Post Page with Static Generation

// app/blog/[slug]/page.tsx
import { getAllPosts, getPostBySlug } from '@/lib/wordpress';

// Generate static paths at build time
export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((post) => ({ slug: post.slug }));
}

// Generate SEO metadata dynamically
export async function generateMetadata({ params }: { params: { slug: string } }) {
  const post = await getPostBySlug(params.slug);
  return {
    title: post.title.rendered,
    description: post.excerpt.rendered.replace(/<[^>]*>/g, '').slice(0, 160),
  };
}

export default async function PostPage({ params }: { params: { slug: string } }) {
  const post = await getPostBySlug(params.slug);

  return (
    <article className="max-w-3xl mx-auto px-4 py-12">
      <h1
        className="text-4xl font-bold mb-4"
        dangerouslySetInnerHTML={{ __html: post.title.rendered }}
      />
      <time className="text-gray-500">
        {new Date(post.date).toLocaleDateString()}
      </time>
      <div
        className="prose prose-lg mt-8"
        dangerouslySetInnerHTML={{ __html: post.content.rendered }}
      />
    </article>
  );
}

Enter fullscreen mode Exit fullscreen mode

Using GraphQL with WPGraphQL + Apollo Client

// lib/apolloClient.ts
import { ApolloClient, InMemoryCache } from '@apollo/client';

export const apolloClient = new ApolloClient({
  uri: process.env.NEXT_PUBLIC_WP_GRAPHQL_URL,
  cache: new InMemoryCache(),
});

Enter fullscreen mode Exit fullscreen mode

# GraphQL query for posts
query GetAllPosts {
  posts(first: 12) {
    nodes {
      id
      slug
      title
      excerpt
      date
      featuredImage {
        node {
          sourceUrl
          altText
        }
      }
    }
  }
}

Enter fullscreen mode Exit fullscreen mode


8. Traditional WordPress vs. Headless WordPress — Deep Comparison

This is the critical decision point. Let's be honest about both sides.

🔒 Security

Aspect Traditional WP Headless WP
Attack surface High (PHP, DB, Admin, Frontend) Reduced (only admin/API exposed)
XSS vulnerability Higher risk Isolated — React sanitizes output
SQL injection via frontend Possible Impossible (no frontend DB queries)
Plugin vulnerabilities Exposed to public traffic API layer shields most exploits
HTTPS enforcement Manual setup needed Naturally enforced by CDN/hosting
Security Score ⭐⭐⭐ ⭐⭐⭐⭐⭐

Stat: 94% of WordPress security breaches are theme/plugin related (Sucuri 2024). In a headless setup, themes are non-existent and only select plugins are used, significantly reducing this risk.

⚡ Performance

Metric Traditional WP Headless WP (Next.js)
TTFB (Time to First Byte) 200–800ms 10–50ms (CDN-cached)
LCP (Largest Contentful Paint) 2.5–6s < 1.5s (with SSG/ISR)
Page size Often 1–3MB < 300KB (optimized)
Core Web Vitals pass rate ~40% ~85–95%
Caching strategy Server-side only CDN + ISR + Browser
Performance Score ⭐⭐⭐ ⭐⭐⭐⭐⭐

Stat: Smashing Magazine's migration to a JAMstack/headless approach reduced their build time by 70% and page load time by 61%.

🎨 Flexibility & Developer Experience

Aspect Traditional WP Headless WP
Frontend language PHP + HTML Any (React, Vue, etc.)
Reusable components ❌ Limited ✅ Full component model
State management ❌ Page reloads ✅ React state/context
Mobile app sharing ❌ Separate codebase ✅ Shared API
CI/CD pipeline Complex Simple (Vercel/Netlify)
TypeScript support ❌ Not native ✅ First-class
Flexibility Score ⭐⭐⭐ ⭐⭐⭐⭐⭐

📈 SEO

Aspect Traditional WP Headless WP (Next.js)
Server-side rendering ✅ Always ✅ SSR / SSG / ISR
Meta tags Via Yoast/RankMath Custom or next-seo
Sitemap Plugin-based next-sitemap or custom
Structured data Plugin-based Manual or libraries
Page speed (SEO factor) ⚠️ Often poor ✅ Excellent
SEO Score ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐

💰 Cost & Complexity

Aspect Traditional WP Headless WP
Hosting cost Low ($5–$30/mo) WordPress ($5–$10) + Vercel (free–$20)
Infrastructure complexity Low Medium
Developer skill required PHP / WP basics React + API knowledge
Content editor learning curve None (familiar) None (same WP admin)
Time to launch Fast Slower initially
Long-term maintenance More plugins = more maintenance Leaner, more controlled

Verdict Summary

Traditional WP:  Security ●●●○○ | Performance ●●●○○ | Flexibility ●●●○○ | SEO ●●●●○
Headless WP:     Security ●●●●● | Performance ●●●●● | Flexibility ●●●●● | SEO ●●●●●

Enter fullscreen mode Exit fullscreen mode

If you're building a simple blog, traditional WordPress is perfectly fine. But if you need performance, multi-channel delivery, security at scale, or want to use modern JavaScript — headless wins every time.


9. Four Real-World Use Cases with Architecture

🏢 Use Case 1: Enterprise Blog / Content Hub

Scenario: A SaaS company runs a high-traffic marketing blog (100k+ monthly visitors) and wants better Core Web Vitals without rebuilding their content workflow.

Architecture:

WordPress (content) → REST API → Next.js (ISR) → Vercel CDN → Users
                              ↘ Mobile App (React Native)

Enter fullscreen mode Exit fullscreen mode

Key Benefits:

  • Editors keep their familiar WordPress dashboard
  • Next.js ISR regenerates pages every 5 minutes — always fresh, always fast
  • Same API feeds a mobile app
  • Vercel edge network delivers content from the nearest CDN node

Result: 62% improvement in LCP, blog pages now pass Core Web Vitals. Zero retraining for editorial team.


🛒 Use Case 2: E-Commerce with WordPress + WooCommerce

Scenario: A fashion brand wants a blazing-fast storefront with custom UX but doesn't want to leave WooCommerce.

Architecture:

WooCommerce (products/orders) → WooCommerce REST API → Next.js Storefront
     ↕ Admin Panel                                     ↕ Cart (Zustand)
WordPress Media Library → CDN (Cloudflare) → Optimized product images

Enter fullscreen mode Exit fullscreen mode

Key Benefits:

  • Custom product pages with React animations
  • Cart managed entirely in React state
  • WooCommerce handles orders, inventory, and payments in the background
  • Checkout can integrate Stripe Elements directly — no WooCommerce checkout page

Result: Conversion rate improved due to faster load times and custom UX. Engineers no longer constrained by WooCommerce page templates.


🎓 Use Case 3: Multi-Language Educational Platform

Scenario: An online learning platform needs to serve content in 6 languages across web and a mobile app.

Architecture:

WordPress + WPML Plugin
        ↓
WPGraphQL (multilingual queries)
        ↓
        ├── Next.js Web App (next-i18next)
        └── React Native Mobile App

Enter fullscreen mode Exit fullscreen mode

Key Benefits:

  • WPML handles translation workflows inside WordPress
  • GraphQL queries can request a specific language locale
  • Same translated content automatically flows to both web and mobile
  • i18n routing in Next.js handles /en/, /fr/, /de/ paths automatically

Result: One content team managing all languages in a single CMS, feeding two platforms simultaneously.


📰 Use Case 4: News / Media Portal with Real-Time Updates

Scenario: A regional news site needs sub-second page loads and real-time article updates without compromising on editorial workflow.

Architecture:

WordPress (CMS) → REST API Webhooks → Trigger ISR revalidation
                                     → Next.js pages updated in <1s
                → WebSockets (breaking news) → Live ticker in React
                → Cloudinary (media optimization) → Fast images

Enter fullscreen mode Exit fullscreen mode

Key Benefits:

  • On-demand ISR revalidation: WordPress sends a webhook when content is published → Next.js immediately regenerates that page
  • Breaking news can be pushed in real-time via WebSocket without a full page rebuild
  • Cloudinary integration replaces WordPress media handling with a professional CDN

Result: Page load time dropped from 4.2s to 0.8s. SEO ranking improved significantly. Editorial team sees no difference in workflow.


10. Final Thoughts

Going headless with WordPress and React isn't about chasing trends — it's about solving real problems that traditional CMS setups genuinely struggle with at scale.

Choose Headless WordPress + React when:

  • ✅ You need exceptional performance and Core Web Vitals scores
  • ✅ Your content needs to reach multiple platforms (web, mobile, IoT)
  • ✅ Your team loves React but your editors love WordPress
  • ✅ You want improved security by minimizing the attack surface
  • ✅ You need flexibility to build custom, brand-defining UX

Stick with Traditional WordPress when:

  • ✅ Your project is simple and time-to-market is critical
  • ✅ You have no React developers on the team
  • ✅ Budget doesn't allow for two separate deployments
  • ✅ Your needs are fully covered by existing WordPress themes/plugins

The good news? You're not making a permanent choice. You can start with traditional WordPress today and incrementally move to headless — one page at a time.

WordPress isn't dying. It's evolving. And pairing it with React is one of the most powerful combinations available to a web developer in 2026.


Happy building! 🚀 If you found this helpful, drop a ❤️ and share it with a developer who's still doing PHP templates in 2026.


Connect with me: [LinkedIn] | [GitHub] | [Dev.to]

Resources: