Last active
January 19, 2018 21:12
-
-
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
This file contains hidden or 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
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