WordPress + React 无头架构搭建指南
📖 目录
- 什么是无头架构?
- 架构图解
- 环境准备
- WordPress后端搭建
- React前端搭建
- 前后端交互
- 部署上线
- 常见问题
🎯 什么是无头架构?
传统WordPress vs 无头WordPress
传统WordPress:
用户访问 → WordPress → PHP模板 → HTML页面
无头WordPress:
用户访问 → React应用 → API请求 → WordPress → JSON数据
核心概念
- WordPress = 只做内容管理(CMS)
- React = 只做用户界面(UI)
- REST API = 连接前后端的桥梁
🏗️ 架构图解
┌─────────────────────────────────────┐
│ WordPress后端 │
│ ┌─────────────────────────────────┐ │
│ │ REST API │ │
│ │ /wp-json/wp/v2/todos │ │
│ │ /wp-json/react-todo/v1/todos │ │
│ └─────────────────────────────────┘ │
│ ┌─────────────────────────────────┐ │
│ │ 自定义文章类型 │ │
│ │ todo_item │ │
│ └─────────────────────────────────┘ │
│ ┌─────────────────────────────────┐ │
│ │ 自定义字段 │ │
│ │ completed, priority │ │
│ └─────────────────────────────────┘ │
└─────────────────────────────────────┘││ HTTP请求▼
┌─────────────────────────────────────┐
│ React前端 │
│ ┌─────────────────────────────────┐ │
│ │ 组件化UI │ │
│ │ TodoForm, TodoList, etc. │ │
│ └─────────────────────────────────┘ │
│ ┌─────────────────────────────────┐ │
│ │ 状态管理 │ │
│ │ useState, useEffect │ │
│ └─────────────────────────────────┘ │
│ ┌─────────────────────────────────┐ │
│ │ HTTP客户端 │ │
│ │ Axios │ │
│ └─────────────────────────────────┘ │
└─────────────────────────────────────┘
🛠️ 环境准备
必需软件
- WordPress 5.0+ (推荐最新版本)
- Node.js 16+
- npm 或 yarn
- 代码编辑器 (VS Code推荐)
开发环境
- 本地WordPress (XAMPP, MAMP, Local等)
- React开发服务器 (Create React App)
🔧 WordPress后端搭建
第一步:创建自定义文章类型
// functions.php
function react_todo_register_post_type() {$args = array('public' => true,'label' => 'Todo Items','show_in_rest' => true, // 🔑 关键:启用REST API'rest_base' => 'todos', // 🔑 关键:API端点名称'supports' => array('title', 'editor', 'custom-fields'),);register_post_type('todo_item', $args);
}
add_action('init', 'react_todo_register_post_type');
作用:
- 告诉WordPress有一个新的内容类型
- 自动生成REST API端点:
/wp-json/wp/v2/todos
第二步:添加自定义字段
// functions.php
function react_todo_add_custom_fields() {// 完成状态字段register_post_meta('todo_item', 'completed', array('show_in_rest' => true, // 🔑 关键:在API中显示'type' => 'boolean','default' => false,));// 优先级字段register_post_meta('todo_item', 'priority', array('show_in_rest' => true, // 🔑 关键:在API中显示'type' => 'string','default' => 'medium',));
}
add_action('init', 'react_todo_add_custom_fields');
作用:
- 为Todo添加额外字段
- 通过REST API暴露给前端
第三步:启用CORS支持
// functions.php
function react_todo_add_cors_headers() {header("Access-Control-Allow-Origin: *");