1

Certain pages on a client site are confidential and I need to restrict access to logged in users. I have looked at various membership plugins but they are overkill for my very basic and specific needs.

I found this snippet which I tested in functions.php

function my_force_login() {
global $post;

if (!is_single()) return;

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

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

When I tested it this code, it restricted a particular blog post EXACTLY how I want it. (the key here is that if the user clicks on a link to a restricted page but is not logged in, they are redirected to a login page, but after they complete login, they should be redirected back to the EXACT original page)

Now I need to modify that code so it will do the following:

Restrict all the pages with a particular parent.

Is that possible? How should the code be modified to achieve this outcome?

Thanks

1

1 Answer 1

2

How about this?

function my_force_login() {
  global $post;

  if (!is_single()) return;

  $restricted_parent_id = 1 // Whatever id you are targeting.

  if ($post->post_parent == $restricted_parent_id && !is_user_logged_in()) {
    auth_redirect();
  }
}

More info on post_parent and other conditional tags here: https://codex.wordpress.org/Conditional_Tags

1
  • This solution caused php errors but it was helpful in that it helped me take this process a step further. I'm now successfully restricting a page. but I still haven't figured out how to restrict all pages with a particular parent.
    – Naomi E
    Mar 22, 2018 at 18:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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