Coding

How to get the current user ID in WordPress

posted on by

WordPress gives us dozens of useful functions to do many things with our favorite CMS; fortunately, many of them are called in a way that perfectly explains what they do – the Latins would say nomen omen. In this post we will see how to get the current user ID, which means the ID of the user that’s currently visiting your website.

WordPress: how to get the current user ID

As stated before, there’s a WordPress function that does exactly what we need: it’s called get_current_user_ID() (check this page for further informations). So, for example, we can do the following to store the ID in a variable.

$current_user = get_current_user_ID();

This will give us the ID we’re looking for – or will return 0 if the user is not logged in.

You can use this value in multiple ways: to store in the database, for example, or to restrict certain content to a single user (maybe you’re developing something in production and don’t want others to see your actions? Not the best practice but…).

That’s what we would do in this last case: let’s say we only want to show content for the user with ID 1…

$current_user = get_current_user_ID();
if( $current_user == 1 ){
    // Show whatever we want...
}

Easy, huh?

If you liked this post and want to be updated on useful WordPress code snippets, as well as our latest theme releases, consider subscribing to our newsletter.

No unwanted spam. We promise.