Jan*_*ana 11 rest wordpress routes wp-api
我需要禁用默认路由WP REST API并添加自定义路由.
我发现这个问题可以帮助我找到以下答案.
Run Code Online (Sandbox Code Playgroud)remove_action('rest_api_init', 'create_initial_rest_routes', 99);但是,这也将删除任何自定义内容类型路由.所以你可以选择使用:
Run Code Online (Sandbox Code Playgroud)add_filter('rest_endpoints', function($endpoints) { if ( isset( $endpoints['/wp/v2/users'] ) ) { unset( $endpoints['/wp/v2/users'] ); } // etc });
但是从这个方面来说,我需要知道所有默认路由并逐个删除,这不是最干净的方法.
我想知道是否有更清洁的方法来实现这一目标?
更新1:
根据克里斯的建议,我会添加更多细节来提问.
目前我正在使用rest_api_init过滤器按照我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';
}
Run Code Online (Sandbox Code Playgroud)
自定义路由运行良好,但不幸的是我无法禁用默认路由,如/wp/v2/posts.
我的问题 :
如何在使用rest_api_init过滤器注册新的自定义路由时取消设置/禁用默认路由?
根据另一个问题,这是目前唯一“干净”的方法。在 WordPress 中处理事物的最干净的方法是使用过滤器和/或操作 - 这允许您与核心交互,而无需对核心进行更改。
通过利用过滤器/操作,您还可以让其他插件有机会在钩子之前/之后对过滤器/操作参数进行操作。
如果您看一下,class-wp-rest-server.php您可以轻松查看与休息相关的所有可用过滤器和操作。
你会特别注意到这一点:
/**
* Filters the array of available endpoints.
*
* @since 4.4.0
*
* @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
* to an array of callbacks for the endpoint. These take the format
* `'/path/regex' => array( $callback, $bitmask )` or
* `'/path/regex' => array( array( $callback, $bitmask ).
*/
$endpoints = apply_filters( 'rest_endpoints', $this->endpoints );
Run Code Online (Sandbox Code Playgroud)
根据我的研究,这是修改(删除、更改或添加)端点的最后一个位置,也是过滤器的确切目的。
顺便说一句,你不需要“一个接一个”地做——你可以重新开始$endpoints = []。
这个问题已经接受了答案.但是,如果有人发现这有用.我们可以轻松删除默认路由.在您的主题(子主题,如果有的话)functions.php或任何自定义插件中添加以下代码
add_filter('rest_endpoints', function( $endpoints ) {
foreach( $endpoints as $route => $endpoint ){
if( 0 === stripos( $route, '/wp/' ) ){
unset( $endpoints[ $route ] );
}
}
return $endpoints;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1939 次 |
| 最近记录: |