我将按照本教程创建WP-API的自定义端点。
在poster上点击/wp-json/custom-plugin/v2/获取所有post-id/进行测试时,我总是会遇到这个错误:
{
"code": "rest_no_route",
"message": "No route was found matching
the URL and request method ",
"data": {
"status": 404
}
}
我在/plugins/custom-plugin/目录中创建了一个定制的plugin.php文件。
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
add_action( 'rest_api_init', 'dt_register_api_hooks' );
function dt_register_api_hooks() {
register_rest_route( 'custom-plugin/v2', '/get-all-post-ids/', array(
'methods' => 'GET',
'callback' => 'dt_get_all_post_ids',
)
);
}
// Return all post IDs
function dt_get_all_post_ids() {
if ( false === ( $all_post_ids = get_transient( 'dt_all_post_ids' ) ) ) {
$all_post_ids = get_posts( array(
'numberposts' => -1,
'post_type' => 'post',
'fields' => 'ids',
) );
// cache for 2 hours
set_transient( 'dt_all_post_ids', $all_post_ids, 60*60*2 );
}
return $all_post_ids;
}
?>
确保对add_action( 'rest_api_init', 'dt_register_api_hooks' );
的回调正在运行。
在我的情况下,我的回调没有被调用,因为我使用add_action('rest_api_init', ...)
太晚了;行动已经开始了。和年一样,我打给register_rest_route()
的电话从未发生过。
我希望我的答案对一些人也有用。
对于一个非常类似的问题,当我在WordPress中设计API时,我在一些网站上也出现了相同的"code": "rest_no_route",...
错误,而在其他网站上没有。我追溯到POST请求被转换为GET请求,所以我的插件无法识别它们。从POST到GET的转换是在WordPress启动之前完成的。我能够通过添加以下标题来确定问题并解决它,如这里详细解释的:
headers: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }