在 WP 中扩展 REST API 的简单方法。
在以下位置创建 2 个文件
1. wp-content/themes/yourTheme/API/wp-rest-api-base.php
2. wp-content/themes/yourTheme/API/wp-rest-api-func.php
然后将这两个文件包含在您当前主题的functions.php
require get_parent_theme_file_path('API/wp-rest-api-base.php');
require get_parent_theme_file_path('API/wp-rest-api-func.php');
现在您有 2 个可以通过以下方式访问的自定义端点
使用POST 方法:http://website.com/wp-json/api/v1/promotions
使用GET 方法:http://website.com/wp-json/api/v1/location_based_notify
ApiDefaultController 构造要求在使用特定端点发出请求时调用方法名称。
注意:您的方法不应返回 JSON 数据,因为它将由 WP REST 结构完成,您只需返回数据数组,然后您的请求将返回 JSON 响应。
wp-rest-api-base.php
<?php
class ApiBaseController extends WP_REST_Controller {
//The namespace and version for the REST SERVER
var $my_namespace = 'api/v';
var $my_version = '1';
public function register_routes() {
$namespace = $this->my_namespace.$this->my_version;
register_rest_route($namespace, '/promotions', array(
array(
'methods' => 'POST',
'callback' => array(new ApiDefaultController('cms_promotions'), 'init'),
)
)
);
register_rest_route($namespace, '/location_based_notify', array(
array(
'methods' => 'GET',
'callback' => array(new ApiDefaultController('location_based_notify'), 'init'),
)
)
);
}
// Register our REST Server
public function hook_rest_server() {
add_action('rest_api_init', array($this, 'register_routes'));
//add_action('rest_api_init', 'my_customize_rest_cors', 15);
}
public function my_customize_rest_cors() {
remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
remove_filter('rest_post_dispatch', 'rest_send_allow_header');
}
}
$ApiBaseController = new ApiBaseController();
$ApiBaseController->hook_rest_server();
wp-rest-api-func.php
<?php
class ApiDefaultController extends ApiBaseController
{
public $method;
public $response;
public function __construct($method)
{
$this->method = $method;
$this->response = array(
'Status' => false,
'StatusCode' => 0,
'StatusMessage' => 'Default'
);
}
private $status_codes = array(
'success' => true,
'failure' => 0,
'missing_param' => 150,
);
public function init(WP_REST_Request $request)
{
try {
if (!method_exists($this, $this->method)) {
throw new Exception('No method exists', 500);
}
$data = $this->{$this->method}($request);
$this->response['Status'] = $this->status_codes['success'];
$this->response['StatusCode'] = 1000;
$this->response['StatusMessage'] = 'success';
$this->response['Data'] = $data;
} catch (Exception $e) {
$this->response['Status'] = false;
$this->response['StatusCode'] = $e->getCode();
$this->response['StatusMessage'] = $e->getMessage();
}
return $this->response;
}
public function cms_promotions($request)
{
$data = array();
return $data;
}
public function location_based_notify($request)
{
$data = array();
return $data;
}
}