• Resolved Mike Witt

    (@mike80222)


    I’m trying to put a short bit of code in functions.php to filter REST calls based on both the route and the logged in user. When I filter ‘rest_authentication_errors’ I can use wp_get_current_user(), but I don’t know how to get the route there. In other filters such as ‘rest_pre_dispatch’ I can get the route from $request, but I (apparently) can’t use wp_get_current_user(). Is there any way I can see the logged in user in the other REST filters? Maybe I need to include something?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    It depends on how the authentication is done. If using cookie authentication, I think you can get the user’s login name from the auth cookies in $_COOKIE. With the login name you can get the user object with get_user_by().

    Thread Starter Mike Witt

    (@mike80222)

    Hi @bcworkz,

    First of all, thanks for replying. I’d like something that works no matter how the authentication is done. I would have thought that if I did the right includes, then the standard user related info would be available. But I guess you’re saying that’s not true.

    Right now what I’m doing is saving the user structure in the rest_authentication_errors filter (where it’s available) into a global variable, and then using that global var in rest_pre_dispatch (where I need it).

    This seemed to me like a pretty bad kludge. But maybe that’s the most straightforward thing I can do?

    What do you think?

    Moderator bcworkz

    (@bcworkz)

    Whatever does the job? ?? It’s considered bad form to rely upon globals in some coding circles, but WP core makes extensive use of them itself. While I agree globals shouldn’t be used as a crutch for poorly thought out coding, I see no problem using them to resolve a sticky situation. While somewhat rare, this wouldn’t be the first time I’ve seen the need to rely on multiple filters to get the right data within scope.

    wp_get_current_user() itself largely relies upon a global value (or the auth cookie I mentioned in some cases). If you’re going to also do so for yourself, you may as well place the current WP_User object you get into the WP global $current_user.

    Thread Starter Mike Witt

    (@mike80222)

    OK, Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Access to logged in user, in REST filters’ is closed to new replies.