WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress Require User Login

299

This post shows a quick and easy way to require that the user is logged in to WordPress in order to gain access to some private content.

For our example, let’s say that we want to display a frontend form only to logged-in users. Here is the basic technique:

if (is_user_logged_in()) {
	// the user is logged in, so display the submission form
	if (function_exists('user_submitted_posts')) user_submitted_posts();
} else { 
	// the user is not logged in, so do something else
	echo 'Please log in to submit posts!';
}

The key to this technique is the WP function, is_user_logged_in(), which basically returns true or false depending on whether or not the current user is logged in to the Admin Area. Basically what this code does is:

  1. Check if the user is logged in, and if so..
  2. Display the USP form
  3. Else, if the user is not logged in..
  4. Do whatever makes sense for your site (e.g., display a message)

Of course, you can replace the USP submission form with whatever content you would like to restrict to logged-in users.

More Information

For more information and techniques, check out these tutorials here at WP-Mix:

Learn more

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!