Page content only visible to logged in users – WordPress

Do you want to create a page only visible for logged-in users?

In my project I wanted to give access to certain pages to only subscribed users in my WordPress site. I also wanted to show the login form in the page so the users didn't need to access through your-site.com/wp-admin

Create a Page Template

First things first, let's create a Page Template so we can assign it to any page we want.

Follow the Codex instructions: http://codex.wordpress.org/Page_Templates

Adding the login form

Alright, now that you have your "Private" custom Page template let's edit it.

In order to show the login form in WordPress we can use this little trick:

<?php // Check if user is logged in if ( !is_user_logged_in() ){ echo "Sign in to see the content!"; wp_login_form( array( 'echo' => true ) ); }else{ // Show content the_content(); } ?>

This snippet will show the login form and, once the user enters the credentials, redirect to the same page showing the content.

5 comments
  • Hello.
    What if i want to show page conent only to logged out user. If user is logged in, then i want to display a message that your are alredy logged in. Please click below to go to homepage.

    Or, is there any way that if user is logged in, and if he/she visit a page – mywebsite.com/signup then he is redirected to another page – mywebsite.com/home.

    Please help….

    U can mail me on vranjan257@gmail.com

  • Can this code be used to restrict content within a page, for example, download links?

  • what about restricting a blog post?

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*