WordPress:如何获取 'init' 挂钩的完整路径?还是另一个钩子更可取?

WordPress: how to get the full path on 'init' hook? or is it another hook preferable?

如果用户不是管理员,我想重定向他们,我在 add_action('init'... 函数中做

但是,如果 URL 路径类似于 /wp-json(v1/...(因此不是用户而是自定义 REST API 请求),我不想重定向用户

我怎样才能抓住请求的 URL 并做出决定?我应该在 init 挂钩中执行此操作吗?

        function redirect_users()
        {

            global $wp;
// $url = get_url();
// if ($url === 'whatever') {
//  return;
// }

            if (get_current_user_id()) {
                $user = get_userdata(get_current_user_id());
                $user_roles = $user->roles;
                if (!in_array('administrator', (array) $user_roles)) {
                    wp_logout();
                    wp_redirect($url);
                    exit;
                }
            }
        }
        add_action('init', '\kw_signup\redirect_non_admin_users', 15);

来自接受的答案

            if (!preg_match('/^wp-json\//', $wp->request)) {
                if (!get_current_user_id()) {
                    wp_redirect($url);
                    exit();
                }
                if (get_current_user_id()) {
                    $user = get_userdata(get_current_user_id());
                    $user_roles = $user->roles;
                    if (!in_array('administrator', (array) $user_roles)) {
                        wp_redirect($url);
                        exit();
                    }
                }
            }
        }
        add_action('parse_request', '\kw_signup\redirect_non_admin_users', 15);

我使用钩子 parse_requesttemplate_redirect,前者接收 wp 对象作为参数

How could I grab the requested URL and decide on that?

要获得请求的 URL,您可以使用 $_SERVER 超全局变量。不过,在您的情况下,我更愿意使用 $wp->request,其中包括 URL.

的路径部分

Should I do this within the init hook?

我认为最适合重定向的钩子是 template_redirect

所以,把它们放在一起:

<?php
namespace kw_signup;

add_action( 'template_redirect', __NAMESPACE__ . '\redirect_non_admin_users' );

function redirect_non_admin_users() {
  global $wp;

  // Check if the requested URL does not start with a specific string
  if ( ! preg_match( '/^wp-json\//', $wp->request ) ) {
    // URL is not a custom REST API request
    // Check if user is an administrator, redirect, …
  }
}