Skip to content

Instantly share code, notes, and snippets.

@nixonmedia
Last active January 19, 2018 21:12
Show Gist options
  • Save nixonmedia/1fc74beb0b17e12f9a272578285e0440 to your computer and use it in GitHub Desktop.
Save nixonmedia/1fc74beb0b17e12f9a272578285e0440 to your computer and use it in GitHub Desktop.
Restrict Wordpress pages a specific page ID and also apply the parent or grand parent template
function wpex_restrict_page_to_logged_in_user() {
// Get global post
global $post;
// Prevent access to page with ID of x and all children of this page
$page_id = 5631;
$parent = $post->post_parent;
$get_grandparent = get_post($parent);
$grandparent = $get_grandparent->post_parent;
if ( is_page() && ( $parent == $page_id || $grandparent == $page_id ) ) {
// Set redirect to true by default
$redirect = true;
//echo 'sub rentry page-';
// If logged in do nor redirect
// You can/should place additional checks here based on user roles or user meta
if ( is_user_logged_in() ) {
//echo 'logged in -- dont redirect me';
$redirect = false;
}
// Redirect people witout access
if ( $redirect ) {
wp_redirect( get_permalink( $page_id ) );
//echo 'redirect me';
}
//apply the same page template to all sub-pages
if($grandparent){
$parent_page_template = get_post_meta($grandparent,'_wp_page_template',true);
}else{
if(!is_page($page_id)){
$parent_page_template = get_post_meta($parent,'_wp_page_template',true);
}
}
//echo 'parent page template = ' . $parent_page_template;
$template = TEMPLATEPATH . "/{$parent_page_template}";
if (file_exists($template)) {
load_template($template);
exit;
}
}
}
add_action( 'template_redirect', 'wpex_restrict_page_to_logged_in_user' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment