您可以通过向 rest_authentication_errors
过滤器添加 is_user_logged_in
检查来要求对所有 REST API 请求进行身份验证。
注意:传入的回调参数可以是 null、WP_Error 或boolean。 参数的类型表示认证状态:
null:尚未进行身份验证检查,钩子回调可能会应用自定义身份验证逻辑。
boolean:表示已执行先前的身份验证方法检查。 Boolean true
表示请求认证成功,boolean false
表示认证失败。
WP_Error:遇到某种错误。
具体方法,在主题functions.php
文件中加入:
add_filter( 'rest_authentication_errors', function( $result ) { // If a previous authentication check was applied, // pass that result along without modification. if ( true === $result || is_wp_error( $result ) ) { return $result; } // No authentication has been performed yet. // Return an error if user is not logged in. if ( ! is_user_logged_in() ) { return new WP_Error( 'rest_not_logged_in', __( 'You are not currently logged in.' ), array( 'status' => 401 ) ); } // Our custom authentication check should have no effect // on logged-in requests return $result; });