WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Tutorials» Force Users To Login Before Reading Posts in WordPress

Force Users To Login Before Reading Posts in WordPress

Last updated on June 21st, 2012 by Editorial Staff
29 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
Force Users To Login Before Reading Posts in WordPress

If your blog has some restricted area that you don’t want to publicize to all visitors, just for members only, then you might want to force users to login before reading these posts. Fortunately, WordPress has a built-in function which can help us to do that.

WordPress: Force Users To Login Before Reading Posts

The function is auth_redirect(), this is how it works: When it is called from a page, it checks to see if the user viewing the page is logged in. If the user is not logged in, they are redirected to the login page. The user is redirected in such a way that, upon logging in, they will be sent directly to the page they were originally trying to access.

By using this function, we can implement our code that check if post is restricted or not, and redirect users to login page if needed.

Just paste the following code into your theme’s functions.php file:

    function my_force_login() {
    global $post;

    if (!is_single()) return;

    $ids = array(188, 185, 171); // array of post IDs that force login to read

    if (in_array((int)$post->ID, $ids) && !is_user_logged_in()) {
    auth_redirect();
    }
    } 

Change the array of post IDs to fit your requirement. After that, open the header.php file and put the following code in the very top:

<?php my_force_login(); ?>

The code is simple, but you can expand it with more options like: require login in some specific categories, make an option page for easy input post IDs, etc.

The function auth_redirect() is available since WordPress 1.5.

Tuan AnhTuan Anh (aka. Rilwis) is a 25 years old blogger and web developer from Vietnam. He is interested in PHP, MySQL as well as Web 2.0 technologies (CSS, Javascript, Ajax). He loves WordPress and all related to it. Follow Rilwis on Twitter to stay update with him. Rilwis’s website: Deluxe Blog Tips
29 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Start Your Own Podcast (Step by Step)

    How to Start Your Own Podcast (Step by Step)

  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

  • How to Properly Move Your Blog from WordPress.com to WordPress.org

  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

34 Comments

Leave a Reply
  1. Nevil Bagul says:
    Jun 12, 2018 at 4:43 am

    how can i use custom redirect page function for login or registration page ?

    Reply
  2. Karl J Samuel says:
    Dec 10, 2017 at 2:06 am

    I want to restrict all posts in my website. If I am using categories should I have to include the category slug or Category ID.
    How to add new posts automatically to the array

    Reply
  3. John Horning says:
    Jan 9, 2017 at 1:13 pm

    For some reason, I could only get this to work by changing
    if (!is_single()) return;
    to
    if (!is_singular(‘page’)) return;

    You can also just remove that line, although I guess it might slow the site slightly.

    Reply
  4. steve says:
    Feb 23, 2016 at 11:34 am

    I’m using Genesis with a child theme. The child theme does not have a header.php but the parent theme (Genesis) does. I tried putting the header.php code (above) into the parent header.php but it did not work. Also did not work with the functions.php code in the child or parent theme. Any thoughts on getting it to work with a child theme?

    Reply
  5. Steven Stieng says:
    Feb 18, 2016 at 3:57 am

    Hard coding ID’s in code is really REALLY bad solution.

    It means that every time you write a new post for members only, you need a programmer to update your code. You do not want to do that.

    Ray Gulick comment is a better option.
    Why? Because members are already registered users with a password, and only they can read the post once they have logged in.

    Reply
  6. Ryan Chart says:
    Oct 21, 2015 at 10:18 am

    Hello, this is great!

    However, when the user clicks the item, it doesn’t redirect to the user login page, but simply a blank white page? How would I fix this?

    Reply
    • Editorial Staff says:
      Oct 21, 2015 at 10:27 am

      If it’s not doing that, then please turn on wp_debug to see the error output. Maybe it’s conflicting with another plugin or code on your site.

      Reply
      • Ryan Chart says:
        Oct 21, 2015 at 10:32 am

        How can I do this? I tried changing the false to true in the wp_config file but nothing happened?

        Reply
  7. Dan says:
    Jan 15, 2015 at 1:01 pm

    Does this work with pages as well as posts?

    Reply
  8. Sam Hughey says:
    May 21, 2014 at 2:20 pm

    I’ve been looking for this and glad I found it. It works, but, I’m using the zM Ajax Login & Register plugin as a custom login page. How can I get this script to redirect users to the zM Ajax Login & Register login page instead of redirecting the user to the main WP login page?

    Thanks,
    Sam Hughey

    Reply
  9. Todd Gechtman says:
    Apr 21, 2014 at 9:14 am

    Hi,
    This is a fantastic solution.
    What would be the full code to require login to specific categories.

    Reply
  10. rotem says:
    Jan 29, 2014 at 11:24 am

    how i can i block all the posts in my site with this code? (not plugin)

    Reply
  11. David says:
    Jan 16, 2013 at 3:26 pm

    According to the codex for auth_redirect(), the function already checks if is_user_logged_in() before doing anything.

    Reply
  12. Donal says:
    Oct 11, 2011 at 11:53 am

    I tried it and it does not work. I am using wordpress 3.2. Any help would be great thanks.

    Reply
  13. SuvechchhaSaha says:
    Oct 1, 2011 at 10:15 pm

    Can you tell me how can i force every user to login to read my post? Then what ID’s should i place on this $ids array?

    Reply
    • wpbeginner says:
      Oct 3, 2011 at 8:10 am

      @SuvechchhaSaha You don’t need to put any IDs. Your code would look like this:if (is_single() && !is_user_logged_in()) { auth_redirect(); }

      Reply
  14. Jimmy says:
    Mar 14, 2011 at 5:29 pm

    Hello, Could you please clarify as to whether this code is valid for wordpress 3.1. Thank you

    Reply
    • Editorial Staff says:
      Mar 14, 2011 at 9:44 pm

      Yes, it should work.

      Reply
  15. Chad Warford says:
    Feb 9, 2011 at 11:13 pm

    Great tip, curious, is there a way to manipulate this code in order to have the entire site force visitors to login, as in they are not able to even arrive on the landing page until logging in?

    Thanks in advance. You are great.

    Reply
    • Editorial Staff says:
      Feb 12, 2011 at 8:21 am

      Using a membership plugin would be a good idea.

      Reply
  16. Brian p says:
    Jul 11, 2010 at 2:31 pm

    How would I make it category based instead of using the array of posts, it would make it so that I wouldnt have to update the array every time I wanted to add a new post that I want to be behind the login.

    I could just apply a category to the post that makes it force a login.

    thoughts?

    Reply
    • Editorial Staff says:
      Jul 12, 2010 at 2:51 am

      You would have to modify the codes slightly from if is_single to if_is_category… You can also use a membership plugin for this (a recommended option).

      Reply
      • Rasheed says:
        Nov 24, 2010 at 3:55 am

        What membership plugins would you recommend for this?

        Reply
        • Editorial Staff says:
          Nov 24, 2010 at 8:03 am

          Wishlist or Magic Members

  17. Amanda says:
    Jul 9, 2010 at 2:04 am

    This is an excellent script, thank you very much for sharing! Is there a way, instead of specific posts, to have the user log in to a specific category? Could you explain, if possible, how this code can be expanded to incorporate categories?
    Thank you so much..

    Amanda

    Reply
    • Editorial Staff says:
      Jul 9, 2010 at 2:29 am

      Get a membership plugin, such as Wishlist or Amember.

      Reply
  18. Ray Gulick says:
    Apr 27, 2010 at 2:55 pm

    Not sure I understand how this has a different effect than setting the visibility of a page to “password protected” on the “Add new page/Edit page” screen in WordPress admin. Can you explain why this function rather than simply selecting a checkbox?

    Reply
    • Editorial Staff says:
      Apr 27, 2010 at 3:03 pm

      Many reasons. One password can get out of control. People might share it which will ruin the purpose of that page. This is so only registered members see the post. You can charge membership fee for your exclusive content using this trick and much more.

      Reply
  19. Mad Mike says:
    Apr 26, 2010 at 3:36 pm

    Oh yeah. Everyone will get that :-)

    Reply
  20. Vivek says:
    Apr 26, 2010 at 2:23 pm

    Thanks for the share. can it would be possible to put this code on thesis theme.

    Reply
    • Editorial Staff says:
      Apr 26, 2010 at 11:04 pm

      You should be able to use it thesis as well because you are not really editing the theme here. You are adding a function in your custom functions.php file and then calling the function in your header hook for thesis.

      Reply
      • Vivek says:
        Apr 27, 2010 at 5:55 am

        thanks for it i will do it on first testing site and then implement it on real site

        Reply
  21. Jal says:
    Apr 26, 2010 at 1:12 pm

    Nice. What I want to ask is it possible to show to a guest user a blank post with a link like Please login to view. Then on the same page a pop up comes where the user logs in to WordPress and immediately the post shows up (using a bit of Ajax). This would be very handy.

    Reply
    • Editorial Staff says:
      Apr 26, 2010 at 11:08 pm

      Very certain that it is possible, but not through this route because the auth_redirect feature actually redirects you to the login page period. No page in between.

      Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
WPForms Logo
WPForms
Drag & Drop WordPress Form Builder Plugin. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2020 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2020)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2020)
    • SiteGround Reviews from 4196 Users & Our Experts (2020)
    • Bluehost Review from Real Users + Performance Stats (2020)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2020 – Step by Step Guide
Deals & Coupons (view all)
Churnly Coupon
Get 30% OFF on Churnly WordPress automated churn-busting plugin.
AccessPress Themes
AccessPress Themes Coupon
Get 15% off on AccessPress Themes collection of premium WordPress themes and plugins.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).
Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress CDN by MaxCDN | WordPress Security by Sucuri.