You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将React项目对接WordPress?实现页面编辑与表单数据收集

React + WordPress 对接实战方案

1. 核心对接方式:WordPress REST API

WordPress 4.7及以上版本默认内置REST API,直接访问你的WordPress站点域名后加/wp-json就能查看完整的接口文档。旧版本(低于4.7)需安装WP REST API插件启用该功能。

2. React 前端请求数据示例

用原生fetch或Axios都能轻松调用接口,以下是获取博客文章列表的React组件示例:

import { useState, useEffect } from 'react';

async function fetchPosts() {
  try {
    const res = await fetch('https://你的WordPress域名/wp-json/wp/v2/posts');
    return await res.json();
  } catch (err) {
    console.error('加载文章失败:', err);
  }
}

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

  useEffect(() => {
    fetchPosts().then(data => setPosts(data));
  }, []);

  return (
    <div className="post-list">
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title.rendered}</h2>
          {/* 渲染富文本内容 */}
          <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
        </article>
      ))}
    </div>
  );
}

3. 自定义API端点(按需扩展)

默认接口满足不了需求时,可在WordPress主题的functions.php中注册自定义端点:

add_action('rest_api_init', function () {
  // 注册自定义接口路径:/wp-json/custom/v1/featured-posts
  register_rest_route('custom/v1', '/featured-posts', [
    'methods' => 'GET',
    'callback' => 'get_featured_posts',
    'permission_callback' => '__return_true' // 公开访问,如需权限可自定义逻辑
  ]);
});

function get_featured_posts() {
  // 查询标记为“精选”的文章
  $args = [
    'post_type' => 'post',
    'meta_key' => '_is_featured',
    'meta_value' => '1'
  ];
  $posts = get_posts($args);
  
  // 格式化返回数据
  return array_map(function($post) {
    return [
      'id' => $post->ID,
      'title' => get_the_title($post->ID),
      'excerpt' => get_the_excerpt($post->ID)
    ];
  }, $posts);
}

之后在React中请求https://你的WordPress域名/wp-json/custom/v1/featured-posts即可获取自定义数据。

4. 身份验证(用于发布/修改内容)

如果需要在React端操作WordPress数据(比如发布文章),有两种常用方式:

  • 应用密码(WordPress 5.6+内置):在WordPress后台用户编辑页面生成应用密码,请求时携带Basic Auth:
async function publishPost(title, content) {
  const username = '你的管理员账号';
  const appPassword = '生成的应用密码';
  const auth = btoa(`${username}:${appPassword}`);

  try {
    const res = await fetch('https://你的WordPress域名/wp-json/wp/v2/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${auth}`
      },
      body: JSON.stringify({
        title,
        content,
        status: 'publish'
      })
    });
    return await res.json();
  } catch (err) {
    console.error('发布文章失败:', err);
  }
}
  • JWT验证:安装JWT Authentication for WP REST API插件,配置后通过Token进行身份验证,适合更复杂的权限场景。

5. 跨域与部署注意事项

  • 若React和WordPress不在同一域名,需在WordPress的functions.php中添加跨域头:
add_action('init', function () {
  header("Access-Control-Allow-Origin: https://你的React站点域名");
  header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  header("Access-Control-Allow-Headers: Content-Type, Authorization");
});

也可使用WP CORS插件可视化配置跨域规则。

  • React项目可部署到静态主机(如Netlify、Vercel),WordPress部署到常规PHP主机即可,两者通过API通信。

6. 进阶优化技巧

  • 用React Query或SWR实现数据缓存,减少重复请求,提升前端性能。
  • 将WordPress配置为纯API服务:自定义主题仅保留必要的PHP代码,不渲染前端页面,节省服务器资源。
  • 配合ACF(高级自定义字段)插件扩展数据,通过REST API返回自定义字段:
add_action('rest_api_init', function () {
  register_rest_field('post', 'custom_fields', [
    'get_callback' => function ($post) {
      return get_fields($post['id']);
    }
  ]);
});

内容的提问来源于stack exchange,提问作者Prains

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:35:45