0

I have 2 lines of code in my header.php file that exclude the header from an array of pages. The code looks like this:

<?php if ( ! is_page( array ( 3599,3653,3684,3732,3737,3758, 3769 ) ) ) { ?>

<?php

With this same array of pages, I need people to be logged in to view them. Is there something I can implement within this line of code that will only apply to those pages so people need to be logged in, and if they're not, it will redirect them to the login page? If they do login, then it should redirect them to the page they were originally trying to look at.

I have tried to create custom templates to achieve this, so I figured this might me the best way. I tried lines of code such as:

get_currentuserinfo();
global $user_ID;
if ( $user_ID == '' ) {
    header( 'Location: /wp-login.php' ); 
    exit(); 
}
1

You are overthinking this ( very dangerous and harmful for programmer/developer )..

Just use this logic in your page template:

<?php

//Check if user is logged in
if( is_user_logged_in() ) {

    //The the stuff you want to show to logged-in users
}
else {

    //Do something else, e.g show notice "You have to be logged in to view this content"
}

?>

Redirecting is a very bad idea because people will get confused easier than you might think!

If I click on a link and it redirects me back without any notice, I will try again.. And just in case one more time.. Then I will leave your site and probably share my bad experience with others because this feels like mocking.



IF you are talking about posts (do not confuse them with pages), I would recommend to:

  • Add meta box to your post edit screen with checkbox
  • Save the checkbox value as post meta if post is saved

Checkbox serves as a flag: if it's checked, show post only to logged-in users.

Then the code in your post template (single-{post-type}.php) would look something like this:

<?php

//Get the post meta from database    
$user_flag = get_post_meta( $post_id, 'user_flag', 'true' );


//Check if checkbox was checked and user is logged in
//                      OR
//If it was not checked, show content to everybody
if( ! $user_flag || $user_flag && is_user_logged_in() ) {


    //The the stuff you want to show to logged-in users
}
else {

    //Do something else, e.g show notice "You have to be logged in to view this content"
}

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.