Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use get_current_user_id() in WordPress?

Tags:

wordpress

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?

like image 866
Flemming Lemche Avatar asked Nov 07 '25 14:11

Flemming Lemche


1 Answers

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 return 0 if the current user is not logged in.

For example, you could do the following:

function hf_Function(){
    $user_ID = get_current_user_id(); 

    if ($user_ID == 0) {
        // The user ID is 0, therefore the current user is not logged in
        return; // escape this function, without making any changes
    }

    // Run your SQL queries here (using WordPress DB class)
    global $wpdb;
    // $wpdb->query($sql);
}
add_action('init', 'hf_Function');

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.

like image 196
Kirk Beard Avatar answered Nov 09 '25 09:11

Kirk Beard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!