0

I need to make a site I am developing be mostly private, accessible by standard Wordpress login. Most plugins are way overkill for what I need, I don't need user roles, tiers, monetization etc. I just need the entire site to be inaccessible, except for the home page and one or two other pages, unless the user logs in with their WP credentials. So accessing any page (except for certain whitelisted pages) would redirect the user to the standard WP login.

I found this script:

function make_wordpress_site_private(){
  global $wp;
  if (!is_user_logged_in() && $GLOBALS['pagenow'] !== 'wp-login.php'){
    wp_redirect(wp_login_url($wp -> request));
    exit;
  }
}
add_action('wp', 'make_wordpress_site_private');

It does 90% of what I need but I am unsure how to whitelist certain pages.

4
  • 1
    You can modify the above code to check for the pages you want to be accessible, otherwise redirect to login: if (!is_user_logged_in() && $GLOBALS['pagenow'] !== 'wp-login.php' && !is_page(array('page1', 'page2', 'page3')) ) You can check the documentation for is_page here: developer.wordpress.org/reference/functions/is_page
    – Kumar
    Commented Mar 9 at 7:26
  • @Kumar I'll look up the reference to see how to reference the pages (slug? path?) and try what you suggest. Thanks!
    – semidivine
    Commented Mar 9 at 15:58
  • That was so simple. Thanks @Kumar for the nudge in the right direction.
    – semidivine
    Commented Mar 9 at 20:40
  • @semidivine I've posted it as answer if you can mark it as answer, thanks.
    – Kumar
    Commented Mar 10 at 6:57

1 Answer 1

2

You can modify the above code to check for the pages you want to be accessible, else redirect to login:

if (!is_user_logged_in() && $GLOBALS['pagenow'] !== 'wp-login.php' && !is_page(array('page1', 'page2', 'page3')) ) 

You can check the documentation for is_page here: https://developer.wordpress.org/reference/functions/is_page

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