logged in/out status

Author Posts

johannesodeg

How to show/hide an element depending on logged in/out status?

-Johannes


Sebastian

Hey Johannes,

It’s likely your theme adds classes to the body tag like “logged-in”. In which case, you could prepend your MT selector with that class to target content for logged in users e.g.

body.logged-in .my-selector {
   display: none;
}

Or to target content for non-logged in users:

body:not(.logged-in) .my-selector {
   display: none;
}

The troubleshooting video shows how to find these classes at 1:57 – in case one accidentally taps into them, but it may be helpful for your purposes too.

If your theme doesn’t add logged in classes, you can install this simple plugin I made to do exactly that. Or copy the following PHP code to your child theme’s functions.php file:

// add the user role class
add_filter('body_class','mt_my_class_names');
function mt_my_class_names($classes) {

	global $current_user;

	$loggedIn = is_user_logged_in();

	// add the logged-in/out class
	$login_staus = $loggedIn ? 'mt-logged-in' : 'mt-logged-out';
	$classes[] = $login_staus;

	// add the user role class
	if ($loggedIn){
		$user_roles = $current_user->roles;
		$user_role = 'role-' . array_shift($user_roles);
		$classes[] = $user_role;
	}

	return $classes;
}

If you use the plugin or sample code, the classes will be a bit different (with mt- prefix) e.g.

body.mt-logged-in .my-selector {
   display: none;
}

I hope that helps. Please let me know if you are still stuck.

Thanks,
Sebastian

You must login or register to reply to this topic.