skip to Main Content

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:

global $current_user = wp_get_current_user();

What do you think?here is the full func code

2

Answers


  1. Try as the image contains syntax error.

    global $current_user;
    $current_user = wp_get_current_user();
    $aleproperty_item['post_author'] = $current_user->ID;
    

    Same code without syntax error.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search