WordPress REST API为开发者提供了通过HTTP请求与WordPress站点交互的强大方式。本文将介绍如何使用JavaScript通过WordPress REST API进行基本操作。
准备工作
在使用WordPress REST API前,需要确保:
- 使用WordPress 4.7或更高版本
- 已启用REST API功能(默认启用)
- 了解基本的JavaScript和AJAX知识
基本请求结构
WordPress REST API的基本端点格式为:
https://your-wordpress-site.com/wp-json/wp/v2/
例如获取文章列表:
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(posts => console.log(posts));
认证方式
对于需要认证的操作(如创建、更新、删除内容),WordPress提供了几种认证方式:
- Cookie认证:适用于已登录用户
- OAuth:更安全的第三方应用认证
- 应用密码:WordPress 5.6+引入的简单认证方式
常见操作示例
1. 获取文章
// 获取最新5篇文章
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts?per_page=5')
.then(response => response.json())
.then(posts => {
posts.forEach(post => {
console.log(post.title.rendered);
});
});
2. 创建新文章
const newPost = {
title: '我的新文章',
content: '这是通过REST API创建的文章内容',
status: 'publish'
};
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_APPLICATION_PASSWORD'
},
body: JSON.stringify(newPost)
})
.then(response => response.json())
.then(post => console.log('创建成功:', post));
3. 更新文章
const updatedPost = {
title: '更新后的标题'
};
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts/123', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_APPLICATION_PASSWORD'
},
body: JSON.stringify(updatedPost)
})
.then(response => response.json())
.then(post => console.log('更新成功:', post));
4. 删除文章
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts/123', {
method: 'DELETE',
headers: {
'Authorization': 'Bearer YOUR_APPLICATION_PASSWORD'
}
})
.then(response => {
if(response.ok) {
console.log('删除成功');
}
});
错误处理
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts/999')
.then(response => {
if(!response.ok) {
throw new Error('请求失败: ' + response.status);
}
return response.json();
})
.then(post => console.log(post))
.catch(error => console.error('错误:', error));
自定义端点
如果需要扩展API,可以在主题的functions.php中添加自定义端点:
add_action('rest_api_init', function() {
register_rest_route('myplugin/v1', '/custom-endpoint', array(
'methods' => 'GET',
'callback' => 'my_custom_endpoint_handler'
));
});
function my_custom_endpoint_handler($data) {
return array('message' => '这是自定义端点');
}
然后通过JavaScript调用:
fetch('https://your-wordpress-site.com/wp-json/myplugin/v1/custom-endpoint')
.then(response => response.json())
.then(data => console.log(data));
最佳实践
- 始终在生产环境使用HTTPS
- 合理限制API访问权限
- 使用缓存减少服务器负载
- 考虑使用wp-api JavaScript库简化操作
通过掌握这些基础知识,您可以开始使用JavaScript通过REST API与WordPress站点进行交互,创建更动态、响应式的Web应用。