什么是WordPress REST API
WordPress REST API是现代WordPress开发的核心功能之一,它允许开发者通过HTTP请求与WordPress站点进行交互。这个基于JSON的API为开发者提供了创建、读取、更新和删除(CRUD)WordPress内容的能力,包括文章、页面、评论、用户等几乎所有WordPress数据。
WordPress文章REST API基础
WordPress文章REST API端点通常遵循以下格式:
/wp-json/wp/v2/posts
基本操作
- 获取文章列表:
GET /wp-json/wp/v2/posts
- 获取单篇文章:
GET /wp-json/wp/v2/posts/<id>
- 创建新文章:
POST /wp-json/wp/v2/posts
- 更新文章:
POST /wp-json/wp/v2/posts/<id>
- 删除文章:
DELETE /wp-json/wp/v2/posts/<id>
认证方式
WordPress REST API提供了几种认证方式:
- Cookie认证:适用于浏览器环境
- OAuth认证:推荐用于第三方应用
- 应用密码:WordPress 5.6+引入的简单认证方式
- JWT认证:通过插件实现的JSON Web Token认证
实际应用示例
获取文章列表
fetch('https://your-site.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(posts => console.log(posts));
创建新文章
fetch('https://your-site.com/wp-json/wp/v2/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
},
body: JSON.stringify({
title: '新文章标题',
content: '文章内容...',
status: 'publish'
})
})
.then(response => response.json())
.then(post => console.log('创建成功:', post));
高级查询参数
WordPress文章REST API支持多种查询参数:
per_page
: 每页显示数量page
: 页码search
: 搜索关键词after/berfore
: 按日期筛选categories
: 按分类筛选tags
: 按标签筛选orderby
: 排序字段order
: 排序方式(asc/desc)
示例:
/wp-json/wp/v2/posts?categories=5&per_page=10&orderby=date&order=desc
自定义字段支持
要处理自定义字段,需要先注册字段或使用ACF等插件提供的REST API支持:
// 在主题的functions.php中注册自定义字段
add_action('rest_api_init', function() {
register_rest_field('post', 'custom_field', array(
'get_callback' => function($post_arr) {
return get_post_meta($post_arr['id'], 'custom_field', true);
},
'update_callback' => function($value, $post) {
update_post_meta($post->ID, 'custom_field', $value);
},
'schema' => array(
'description' => '自定义字段描述',
'type' => 'string'
)
));
});
性能优化建议
- 使用
_fields
参数只请求需要的字段 - 合理使用缓存
- 限制每页返回数量
- 考虑使用GraphQL作为替代方案处理复杂查询
常见问题解决
- 403禁止访问错误:检查认证是否正确
- 404端点不存在:确保WordPress版本支持REST API
- CORS问题:添加适当的CORS头
- 性能问题:优化查询,减少请求数据量
结语
WordPress文章REST API为开发者提供了强大的内容管理能力,无论是构建移动应用、单页应用(SPA)还是与其他系统集成,都能发挥重要作用。掌握REST API的使用可以大大扩展WordPress的应用场景,为现代Web开发提供更多可能性。