[wp-trac] [WordPress Trac] #42412: Calling get_current_user_id() and setting $current_user gives unexpected behaviour

WordPress Trac noreply at wordpress.org
Fri Aug 16 14:20:56 UTC 2019


#42412: Calling get_current_user_id() and setting $current_user gives unexpected
behaviour
--------------------------+------------------------------
 Reporter:  gertmeeusen   |       Owner:  (none)
     Type:  defect (bug)  |      Status:  closed
 Priority:  normal        |   Milestone:  Awaiting Review
Component:  General       |     Version:  4.8.3
 Severity:  normal        |  Resolution:  worksforme
 Keywords:                |     Focuses:
--------------------------+------------------------------
Changes (by donmhico):

 * status:  new => closed
 * resolution:   => worksforme


Comment:

 Hello @gertmeeusen. Welcome to our trac. Here are a few things that might
 help you.

 1. Your code above is best to be called inside the `init` hook as the
 `User` is already authenticated at that point. See
 https://codex.wordpress.org/Plugin_API/Action_Reference.

 You can do this by wrapping your code above inside a function e.g
 `my_function()` then using `add_action( 'init', 'my_function' )`. See
 https://developer.wordpress.org/reference/functions/add_action/.

 2. In you want to call the global `$current_user` var. You need to do it
 like this.
 {{{#!php
 <?php
 global $current_user;

 var_dump( $current_user );
 }}}

 But again, it's better to use WP functions like `wp_get_current_user()` or
 `get_current_user_id()` than the global var.

 See
 https://developer.wordpress.org/reference/functions/wp_get_current_user/
 https://developer.wordpress.org/reference/functions/get_current_user_id/

 I'll be marking this as `worksforme` since trying your code in `init` hook
 works as intended.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/42412#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list