Skip to content

Instantly share code, notes, and snippets.

@kimcoleman
Created August 29, 2019 13:01
Show Gist options
  • Save kimcoleman/c5925d4c3dee88a1ce2b5d32d06ae1b9 to your computer and use it in GitHub Desktop.
Save kimcoleman/c5925d4c3dee88a1ce2b5d32d06ae1b9 to your computer and use it in GitHub Desktop.
Restrict your WordPress site for logged in users only.
<?php
/**
* Restrict your WordPress site for logged in users only.
*
*/
function my_require_user_login() {
global $current_user;
// Allow logged in users.
if ( is_user_logged_in() ) {
return;
}
// Allow all visitors to view these public pages.
$okay_pages = array(
'welcome',
);
if ( is_page( $okay_pages ) ) {
return;
}
// Allow all visitors to view the homepage.
if ( is_front_page() ) {
return;
}
// Allow all visitors to view these Theme My Login pages.
$tml_pages = array( 'login', 'lostpassword', 'resetpass', 'logout', );
if ( is_page( $tml_pages ) ) {
return;
}
// Allow all visitors to view URLs with the word login in it.
if ( strpos( $_SERVER['REQUEST_URI'], 'login' ) !== false ) {
return;
}
// Redirect everyone else to the login page.
wp_redirect( home_url( 'wp-login.php?redirect_to=' . urlencode( $_SERVER['REQUEST_URI'] ) ) );
}
add_action( 'template_redirect', 'my_require_user_login' );
@laurenhagan0306
Copy link

This recipe is included in the blog post on "You don’t need a membership plugin." at Paid Memberships Pro here: https://www.paidmembershipspro.com/you-do-not-need-membership-plugin/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment