How to Display a Message When the User is Already Logged In

Introduction

Are you using the WPForms User Registration addon and want to display a message when the user is already logged in on all of your login forms? By default, if the user is already logged in, the login form will not display. Providing a small message to let the user know they are already logged in and a useful to in order to reduce any confusion.

In this tutorial, we’re going to create a user login form with the User Registration addon and then add a small code snippet to our site that will display a message if the user is currently logged in.

Creating the login form

First, let’s create a login form. If you need help in creating your form, please review this documentation.

Create your user login form

Now that our form is created, we can add it to a page in WordPress.

Add your form to any WordPress post, page or widget

Setting the user option in the form builder

You can choose to show or hide the form if the user is logged in from within the form builder. But for this tutorial, we’re going to enable the Hide Form option.

Inside the form builder, click on Settings and then under General, enable the Hide the form if a user is already logged in.

In the form Settings under the General tab, make sure to enable the option to hide the form if the user is already logged in

Adding the code snippet

Now it’s time to add the code snippet to your site.

For any assistance in how to add code snippets to your site, please review this tutorial.

/**
 * Display a message to users already logged in
 *
 * @link   https://wpforms.com/developers/how-to-display-a-message-when-the-user-is-already-logged-in/
 *
 */

function wpf_dev_logged_in_message( $form_data, $form ){ 
   if ( is_user_logged_in() && ! empty( $form_data['settings']['user_login_hide'] ) ) {
       echo '<p>' . __( 'You are currently logged in to the site.', 'textdomain' ) . '</p>';
   }
} 

add_action('wpforms_frontend_not_loaded', 'wpf_dev_logged_in_message', 10, 2);

The first part of this code snippet will check to see if the user is logged in and check to see if the setting to hide the form if the user is already logged in is enabled, if it matches those two requirements, the message will display to the user.

Now your message will display when user is already logged in

This snippet will only work for the login form, not for the registration form.

And that’s it! Would you like to automatically log in your users once they’ve registered to your site? Take a look at our tutorial on How to Automatically Log in Users After Registration.