Restrict page content visibility to logged in users

Have you ever come into a situation where you want to restrict your pages content to registered users only?

If so, then this little snippet of code can help you do that. You will need to place the snippet inside the loop of your theme’s page.php file. First, find the function responsible for displaying content ‘the_content();’ and replace it with the snippet provided below.

Basically what this function does is that it checks if the user is logged in or not. If he is logged in it grants him access to read the content of all pages. If he isn’t logged in it displays the login form instead.

PHP
<?php
if ( !is_user_logged_in() ){
	echo "Please login to see the content!";
	wp_login_form( array( 'echo' => true ) );
}else{
	the_content();	
}
?>

If you want to restrict the content of specific pages only on your WordPress website then you will need to create an additional page template. To create one,  just copy the content of your page.php file and paste it into a new PHP file. Then name this file restricted-page.php.  Make sure as well to add a descriptive name at the top of your template file just after the PHP opening tag. A name like this  Template Name: Restricted Pages will be a good one.  If you need more information about creating new page templates please check the official WordPress Page Templates guide.

Once your new template page is created make sure to introduce the snippet above where indicated inside the loop. Then go to your WordPress dashboard and edit the pages you wish to restrict its content to logged in users. Finally, assign the newly created custom template to each of these pages.

If you need help just leave us a comment and we will do our best to help you out.