PHPTutor.info

Require Users to Login to a WordPress Blog

I have had several clients over the years who have wanted to limit access to sites to registered users. With the growing acceptance of WordPress as a simple CMS for client websites, this need for restricting access is needed in WordPress too.

Fortunately, limiting access is as simple as dropping a small if-then block in to your theme. The code block simply checks the user id of the currently browsing user. If this value is not missing, then they are logged in. Simple. If they are not logged in, you just force a redirect to the login page.

This solution may not address all of your needs, but seeing how simple the solution is should give you confidence in developing WordPress based solutions that will meet them.

Implementing This Code:

  • Insert the if-them block from the block below as the first line of code in your activated WordPress theme's index.php file (right after the opening '<?php'). If you activate a different theme you will need to do the same modification there, otherwise this code will not be accessed (meaning, your blog will be wide open again).
  • You should always test this when you upgrade your WordPress installation. While it is a simple statement, you can not guarantee that '$user_ID' will always be used by WordPress to identify the current user. Yes, it is likely that this particular variable will never be obsolete. However, the moment you fix it in your mind that it will never happen, it will.

<?php
if ($user_ID == '') { header('Location: wp-login.php'); exit; } ?>


Side Notes about this approach:

  • I always drop in an exit command after a header redirect. While I have not seen an issue in quite a while, on occasion in the past, I would see the line of code after a header call actually execute. While I know this shouldn't happen, and may have been more a case of programmer error, I always drop in an exit after a header redirect.

About the Author:
Esoomllub has been coding professionally for well over 20 years. He is now basically coding on his own sites, and only occasionally takes on contract work. You can read some of his rants and PHP programming thoughts on his blog.

Recommended PHP Scripts

CuteNews
CuteNews

Cute news is a powerful and easy for using news management system that use flat files to store its database. It supports comments, archives, search function, image uploading, backup function, IP banning, flood protection etc