Showing content to users who are logged in (and who are not logged in) to WordPress

We recently needed a simple way to show content to users who weren’t logged into a client website. Initially, we used this shortcode which works very well.

But then we needed to show an alternate text if the user wasn’t logged in. To accomplish this, we adapted the shortcode as follows:

function check_user($atts, $content = null) {
	
	if($atts['for_not_logged_in'] == "yes") {
		//check that the user is logged in
		if ( is_user_logged_in() ){
			//user IS logged in so HIDE the content
			return;
		}
		else {
			//user IS NOT logged in so SHOW the content
			return $content;
		}
	} else {
		//Otherwise no attributes in shortcode so default behaviour (show only to those logged in)
		//check that the user is logged in
		if ( is_user_logged_in() ){
			//user IS logged in so SHOW the content
			return $content;
		}
		else {
			//user IS NOT logged in so HIDE the content
			return;
		}
	}	
}

//add a shortcode which calls the above function
add_shortcode('loggedin', 'check_user' );

To add this to your website, we recommend following these steps:

  1. Use a child theme
  2. In your child theme’s root folder, make a folder called “includes”
  3. In the “includes” folder, make a file called “add-shortcode-if-user-is-logged-in.php”
  4. Paste the above code into that file
  5. In your child theme’s root folder, make a file called “functions.php”
  6. In the functions.php file, add this line:
    require_once('includes/add-shortcode-if-user-is-logged-in.php');

Now, if you want to add text to your website that only logged-in users can see, enter this shortcode:

  • [loggedin]This is text only logged-in users can see.[/loggedin]

And if you want to add text to your website that only non-logged-in users can see, enter the same shortcode with the extra attribute:

  • [loggedin for_not_logged_in=”yes”]This is text only non-logged-in users can see.[/loggedin]

Recent Posts