WP-REST API 的自定义路由端点给出“code”:“rest_no_route”,错误

2024-03-12

我正在关注this https://deliciousbrains.com/wp-rest-api-customizing-endpoints-adding-new-ones/创建 WP-API 自定义端点的教程。

我总是在点击时遇到这个错误/wp-json/custom-plugin/v2/get-all-post-ids/ on postman去测试 :

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

我在 /plugins/custom-plugin/ 目录中创建了一个 custom-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()甚至从未发生过。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WP-REST API 的自定义路由端点给出“code”:“rest_no_route”,错误 的相关文章

随机推荐