0

I'm writing a simple plugin that runs when a user logs in and logs out. (I'm a PHP n00b and this is purely educational)

It references $current_user (defined as global in the function). And it all works as it should.

Except, of all the code snippets I've seen that reference $current_user, some call wp_get_current_user() beforehand, and some don't.

My question is... should wp_get_current_user() always be called before accessing $current_user - or is it safe to presume wp_get_current_user() has already been called (with the caveat the code is running in the WordPress Admin panel - so a user MUST logged in)?

Reason I ask is... it seems inefficient to call a function that's already been called (and if a user's logged in then it must have been called, right?), but also we should never presume anything (what if, for some bizarre reason, the name $current_user is changed in Core in the future).

Of course, there's a third option that's only just sprung to mind... test whether $current_user is already set/defined and if it isn't, call wp_get_current_user().

TBH this last option seems like the best 'efficiency vs robustness' compromise - but I'm still curious to hear which people think is the best way and why.

1 Answer 1

1

Yes, as a best practice, you should call wp_current_user() because you can't assume that $current_user is set (or if it is set correctly with the user you're after).

Of course, there's a third option that's only just sprung to mind... test whether $current_user is already set/defined and if it isn't, call wp_get_current_user().

Actually, that's kind of what happens already. wp_get_current_user() is just a wrapper for the private method _wp_get_current_user(), so you can look at that function to see what it does. The first thing it does is check if $current_user exists and is populated, and if so, it returns $current_user.

To address your question of efficiency/inefficiency, since the method is already checking to see if $current_user is loaded, it would actually be more inefficient if you were doing it, then running wp_get_current_user() since that would be an unnecessary step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.