Watching video about plugin creation and 2 lines af code make me stuck.
Maybe you know why the author call get_current_user() and not assign its value?
Maybe there is an error? Should be like that:
When using the global keyword, you can’t assign a value, it is just for bringing global variables into the local scope. That specific function ultimately sets a global variable, and doing it that way (although the order doesn’t matter) gives you access to that variable.
That function, however, also returns the same value, so there is no need to bring a global scoped value into local, it can just be used directly.
Older WordPress code tended to use more global variables, but in the recent years there’s been a trend of trying to encapsulate them in helper functions so some of the “magic” goes away, and this author might have some legacy code or mindset.
EDIT
There used to be a function called get_currentuserinfo that was deprecated in 4.5. That function did the following:
Populate global variables with information about the currently logged in user.
And the pattern for using it was:
global $current_user;
get_currentuserinfo();
Although I don’t know which video you watched, I’m guessing that the person just blindly replaced get_currentuserinfo() with wp_get_current_user() and although weird, it technically works still.
2
Answers
Try as the image contains syntax error.
Same code without syntax error.
When using the
global
keyword, you can’t assign a value, it is just for bringing global variables into the local scope. That specific function ultimately sets a global variable, and doing it that way (although the order doesn’t matter) gives you access to that variable.That function, however, also returns the same value, so there is no need to bring a global scoped value into local, it can just be used directly.
Older WordPress code tended to use more global variables, but in the recent years there’s been a trend of trying to encapsulate them in helper functions so some of the “magic” goes away, and this author might have some legacy code or mindset.
EDIT
There used to be a function called
get_currentuserinfo
that was deprecated in 4.5. That function did the following:And the pattern for using it was:
Although I don’t know which video you watched, I’m guessing that the person just blindly replaced
get_currentuserinfo()
withwp_get_current_user()
and although weird, it technically works still.