WordPress 路由

一,添加路由

add_action( 'rest_api_init', function () {
    register_rest_route( 'rangtuo/v1', '/author/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'test_callback',
    ));
});

function test_callback($request){
    $request->get_url_params();
    $request->get_query_params();
    $request->get_body_params();
    $request->get_json_params();
    $request->get_default_params();
    $request->get_file_params(); // 上传的文件
    
    $data = array(
        "message" => "hello",
        "test" => __('dada', 'rangtuo'),
        "dodo" => __('dodo', 'rangtuo')
    );
    $response = new WP_REST_Response($data);
    $response->set_status(403);
    return $response;
}

二,RESTful API 推荐的目录结构

项目中,接口模块目录结构:

├── api                               # 接口目录
|    ├── orders                       # 订单模块
|    |    ├── orders.controller.php   # 订单控制器
|    |    ├── orders.service.php      # 订单服务
|    |    └── routes.php              # 路由文件
|    └── stars                        # 收藏点赞模块
|    ├── auth                         # 注册登录模块
|    ├── ...                          # 其他模块

三,RESTful API 推荐的路由对应方法

请求 路径 说明 对应方法
GET /items 返回资源对象的列表(数组) index
GET /items/:id 返回单个资源对象 read
POST /items 返回新生成的资源对象 store
PUT /items/:id 返回完整的资源对象 update
PATCH /items/:id 返回完整的资源对象 update
DELETE /items/:id 返回一个空文档 destory

收藏 0
评论
WordPress 基础
WordPress 输入安全
2023-05-04 11:08:23
WordPress 主题开发
WordPress 常用的路径
2023-05-04 11:21:58
生成中...
登录
注册
重置密码