我在创建自定义端点以扩展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;
}
但实际上我应该在哪里添加这些东西?另外,我研究了很多并看到了高级端点控制器的实践,有人可以帮我吗?或者我需要创建自己的插件?
答案 0 :(得分:3)
所有代码都转到主题的functions.php
文件或插件。注册REST路由后,可以通过以下URL访问:
www.example.com/wp-json/myplugin/v1/foo
答案 1 :(得分:0)
为了节省一些像我这样的时间,这正是我在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' );
现在转到浏览器并输入:
这应该有助于您开始创建自定义端点