Last active
May 4, 2023 12:46
-
-
Save kimcoleman/93995037e3c6fb6cbceed82b207e9ec8 to your computer and use it in GitHub Desktop.
Restrict specific pages in your WordPress site for logged in users only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Restrict specific pages in your WordPress site for logged in users only. | |
* | |
*/ | |
function my_restricted_pages_require_user_login() { | |
global $current_user; | |
// Allow logged in users. | |
if ( is_user_logged_in() ) { | |
return; | |
} | |
// Restrict all visitors from these pages. | |
$restricted_pages = array( | |
'private-page-1', | |
'private-page-2', | |
); | |
if ( is_page( $restricted_pages ) ) { | |
wp_redirect( home_url( 'wp-login.php?redirect_to=' . urlencode( $_SERVER['REQUEST_URI'] ) ) ); | |
} else { | |
return; | |
} | |
} | |
add_action( 'template_redirect', 'my_restricted_pages_require_user_login' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment