WordPress REST API 外部请求处理指南

WordPress REST API 提供了强大的接口,允许外部系统与WordPress进行安全交互。以下是完整的实现方案:

一、基础API配置

1. 启用REST API

wp-config.php中添加:

define('WP_REST_API', true); // 默认已启用
define('WP_REST_AUTH_REQUIRED', false); // 是否要求认证

2. 查看可用端点

访问/wp-json/可查看所有注册的REST API端点

二、处理外部GET请求

1. 注册GET端点

add_action('rest_api_init', function() {
register_rest_route('myplugin/v1', '/external-data', [
'methods' => 'GET',
'callback' => 'handle_external_get',
'permission_callback' => '__return_true'
]);
});

function handle_external_get($request) {
$params = $request->get_params();

// 验证参数
if (empty($params['id'])) {
return new WP_Error('missing_id', '缺少ID参数', ['status' => 400]);
}

// 获取数据
$post = get_post(absint($params['id']));

if (!$post) {
return new WP_Error('post_not_found', '文章不存在', ['status' => 404]);
}

// 返回格式化数据
return [
'id' => $post->ID,
'title' => $post->post_title,
'content' => apply_filters('the_content', $post->post_content),
'date' => $post->post_date
];
}

三、处理POST/PUT请求

1. 数据接收与验证

add_action('rest_api_init', function() {
register_rest_route('myplugin/v1', '/submit-data', [
'methods' => 'POST',
'callback' => 'handle_external_post',
'permission_callback' => function() {
return current_user_can('edit_posts');
}
]);
});

function handle_external_post($request) {
$data = $request->get_json_params();

// 数据验证
$errors = [];
if (empty($data['title'])) {
$errors[] = '标题不能为空';
}

if (!empty($errors)) {
return new WP_Error('invalid_data', $errors, ['status' => 400]);
}

// 创建新文章
$post_id = wp_insert_post([
'post_title' => sanitize_text_field($data['title']),
'post_content' => wp_kses_post($data['content']),
'post_status' => 'publish',
'post_type' => 'post'
]);

if (is_wp_error($post_id)) {
return $post_id;
}

return [
'success' => true,
'post_id' => $post_id,
'edit_link' => get_edit_post_link($post_id, 'raw')
];
}

通过以上方法,可以构建安全、高效且功能完善的WordPress REST API接口,满足各种外部系统集成需求。建议在生产环境中启用HTTPS加密传输,并配合适当的认证机制确保数据安全。

我爱主题网 自2012
主题:260+ 销售:1000+
兼容浏览器

电话咨询

7*12服务咨询电话:

1855-626-3292

微信咨询