wordpress - 禁用 WP REST API 的默认路由

标签 wordpress rest routes wp-api

我需要禁用 WP REST API 的默认路由并添加自定义路由。

我找到了this question这有助于我找到以下答案。

remove_action('rest_api_init', 'create_initial_rest_routes', 99);

However this will also remove any custom content type routes. So instead you may choose to use:

add_filter('rest_endpoints', function($endpoints) {
    if ( isset( $endpoints['/wp/v2/users'] ) ) {
        unset( $endpoints['/wp/v2/users'] );
    }
    // etc
});

但是通过这种方式,我需要知道所有默认路由并一一删除,这不是最干净的方法。

我想知道是否有更干净的方法来实现这一目标?

更新1:

根据克里斯的建议,我会为问题添加更多详细信息。

目前,我正在使用 rest_api_init 过滤器,按照我在 this article 上找到的以下代码,使用 register_rest_route 方法添加自定义路由。 .

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', '/sample/', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

function my_awesome_func( $data ) {
  return 'somthing';
}

自定义路由效果很好,但不幸的是我无法禁用默认路由,例如/wp/v2/posts

我的问题:

如何在使用 rest_api_init 过滤器注册新的自定义路由时取消设置/禁用默认路由?

最佳答案

此问题已接受答案。但如果有人觉得这有用的话。 我们可以轻松删除默认路由。在您的主题(子主题,如果有)的functions.php或任何自定义插件中添加以下代码

add_filter('rest_endpoints', function( $endpoints ) {

    foreach( $endpoints as $route => $endpoint ){
        if( 0 === stripos( $route, '/wp/' ) ){
            unset( $endpoints[ $route ] );
        }
    }

    return $endpoints;
});

关于wordpress - 禁用 WP REST API 的默认路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42757726/

相关文章:

model-view-controller - Grails-路径中的用户名

css - 只有 wp_enqueue_style 的第一行被执行

php - 如何使 h1 和 h1 都呈现在同一行上

wordpress - WP 插件开发 - 短代码上的条件 CSS

javascript - 如何将 _dirname 与同级目录一起使用

ruby-on-rails - Rails 路线 : Wrong singular for resources

wordpress - WordPress 中的相对 URL

Java 从 JWT token 获取主题

web-services - 在没有任何专用 IP 地址的 EC2 服务器上安装 SSL 证书

javascript - Node.js Express : Redirect or render on post