创建自定义端点Wordpress

3
我在创建自定义端点以扩展我的WordPress应用程序时遇到了困难。
设置WordPress模块后,我可以通过给定的链接访问JSON数据:http://localhost/wordpress/wp-json/ 我使用链接https://developer.wordpress.org/rest-api/reference/测试了不同的端点。
现在我正在尝试创建自己的端点,但是经过多次研究,我只能找到类似以下内容:
add_action( 'rest_api_init', 'myplugin_register_routes' );

并且然后。
function myplugin_register_routes() {
  register_rest_route( 'myplugin/v1', 'foo', array(
    'methods'  => WP_REST_Server::READABLE,
     'callback' => 'myplugin_serve_route',
  ));
}


function myplugin_serve_route( WP_REST_Request $request ) {
// Do something with the $request
// Return either a WP_REST_Response or WP_Error object
return $response;
}

但是,我应该在哪里添加这些内容呢?我进行了大量的研究,并查看了高级终端控制器实践,有人可以帮助我吗?还是我需要创建自己的插件?

2个回答

3
所有代码都放在主题的functions.php文件中,或者一个插件中。注册了REST路由之后,可以通过以下URL访问它:

www.example.com/wp-json/myplugin/v1/foo


1
为了节省像我这样的人一些时间,这就是我在function.php文件中发布的内容。
/**
 * Custom API
 * 
 * This is our callback function that embeds our phrase in a WP_REST_Response
 */
function prefix_get_endpoint_phrase() {
    // rest_ensure_response() wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned.
    // I guess here we grab our data in the return method
    return rest_ensure_response( 'Hello World, this is my WordPress REST API' );
}

/**
 * This function is where we register our routes for our example endpoint.
 */
function prefix_register_example_routes() {
    // register_rest_route() handles more arguments but we are going to stick to the basics for now.
    register_rest_route( 'hello-world/v1', '/my-command', array(
        // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
        'methods'  => WP_REST_Server::READABLE,
        // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
        'callback' => 'prefix_get_endpoint_phrase',
    ) );
}

add_action( 'rest_api_init', 'prefix_register_example_routes' );

现在打开你的浏览器并输入:

http://yoursite.com/wp-json/game-thunder/v1/featured-games

这应该可以帮助您开始创建自定义端点


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接