I’m trying to figure out how to use the function get_current_user_id()
properly.
I need it for user data separation just like a normal PHP code would use $_SESSION
.
I’ve found the following code sample which I’ve placed in Function.php
and it works fine, but it seems to be executed on every page which is not the intention.
function hf_Function(){
$user_ID = get_current_user_id();
_SESSION["uid"] = user_ID;
}
add_action('init', 'hf_Function');
I just need it to execute once and save the information in a $_SESSION
variable or a global variable that I can access from my own PHP pages.
I tried to put the lines above in my own PHP script but it doesn’t seem to work.
Is this the right way to do it or am I doing something wrong?
What is best practice when it comes to using get_current_user_id()
and the other built-in functions?
Based on your example code, there is no benefit to you storing the user_id in the
$_SESSION
.You can use the
get_current_user_id()
method throughout the site. It will return the current users ID if they are logged in, or it will return0
if the current user is not logged in.For example, you could do the following:
Because you’re using the
init
action, this function will run on every page load. You may need to change the action, depending on what you’re trying to achieve. This answer on WordPress SE might be useful to help you understand the WordPress lifecycle.