WP-REST API 的自定义路由端点给出“代码":“rest_no_route",错误 [英] Custom route endpoint for WP-REST API gives "code": "rest_no_route", error

查看:87
本文介绍了WP-REST API 的自定义路由端点给出“代码":“rest_no_route",错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照 this 教程创建自定义端点到 WP-API .

I am following this tutorial to create custom end points to WP-API .

postman 上点击 /wp-json/custom-plugin/v2/get-all-post-ids/ 进行测试时,我总是收到此错误:

I am always getting this error on hitting /wp-json/custom-plugin/v2/get-all-post-ids/ on postman to test :

{
    "code": "rest_no_route",
    "message": "No route was found matching
    the URL and request method ", 
    "data": {
        "status": 404
    }
}

我在/plugins/custom-plugin/目录中创建了一个 custom-plugin.php 文件.

I have created a custom-plugin.php file in /plugins/custom-plugin/ directory .

<?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' ); 的回调正在运行.

Ensure your callback to add_action( 'rest_api_init', 'dt_register_api_hooks' ); is being run.

就我而言,我的回调没有被调用,因为我使用 add_action('rest_api_init', ...) 太晚了;行动已经开始.就像这样,我对 register_rest_route() 的调用从未发生过.

In my case, my callback was not being called because I was using add_action('rest_api_init', ...) too late; the action had already fired. As in, my call to register_rest_route() never even happened.

这篇关于WP-REST API 的自定义路由端点给出“代码":“rest_no_route",错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆