我需要禁用 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/