WordPress Force User Redirect to Login Page

Today’s discussion is about how to force the user to redirect to the login page programmatically in WordPress. This functionality is usually required when the website owner decides to limit his articles to be viewed by private users only.

Following is an example

add_action( 'init', 'qaisarsatti_website_redirect' );
  function qaisarsatti_website_redirect() {

  if ( !is_user_logged_in() ) {
        $loginUrl = wp_login_url();
        $currentUrl = home_url($_SERVER['REQUEST_URI']);
        if($loginUrl!=$currentUrl) {
            wp_redirect( wp_login_url());  
          exit;
      }
     }
  }

Here is an available free extension WordPress Private Website.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!