Developing for WordPress and want to know how check if a user is logged in? Keep reading for useful user PHP code snippets.
Sometimes you want to add functionality or display something only for logged in users. This is easy using WordPress’ built-in is_user_logged_in() function. This quick tip will show you how to check if a user is logged in WordPress.
To use this you’ll have to be familiar with programming in PHP. If you are editing a theme we recommend creating a child theme first. This will allow you to edit code in your theme without it breaking when the parent theme is updated. Additionally you can add code with a custom plugin or Code Snippets plugin.
Check if User is Logged Into WordPress Function
Here’s an example using the is_user_logged_in() function to display a logout link for logged in users and a login link for logged out users.
You can use this in your theme’s function.php to add functionality specific to logged-in users. It will also work in your theme’s index.php, archive.php, single.php, etc for all kinds of functionality for logged in users.
Check if Current User is Administrator in WordPress
If you want to add functionality only for logged in admins this can be done with the current_user_can() function. By using current_user_can(‘administrator’) in an if statement it’ll allow you to check if the current user is a site admin.
Additionally, you can target a specific capability of a user.
This is useful if you have created custom roles on your site. There are plenty of WordPress capabilities to target your if statement. For example, manage_options is good for targeting admins while edit_posts is good for targeting editors.
Additionally if you don’t want to use PHP you can change styling of the site using CSS when a user is logged in. WordPress adds the class “logged-in” to the body tag of your site when a user is logged in.
For example this snippet below will change the background color of your site when a user is logged in.
In addition to using is_user_logged_in() in your theme and functions.php you can also include this in a custom WordPress plugin for the same effect.