Created
May 25, 2016 11:22
-
-
Save DrizzlyOwl/387eafeac23f798bec8b9b1c3a36dd17 to your computer and use it in GitHub Desktop.
WordPress protected page template
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 | |
/** | |
* Load a different template if a user without 'contributor' permissions lands on a page which uses the | |
* tpl-protected.php template | |
* | |
* @param $template | |
* @return string | |
*/ | |
function filter_protected_page( $template ) { | |
global $post; | |
$using_template = is_page_template('tpl-protected.php'); | |
$parent_using_template = get_page_template_slug($post->post_parent); | |
$user_has_perms = current_user_can('edit_posts'); | |
// If the current post or it's parent post is using the tpl-protected.php template but the user | |
// does not have permission to view the page then load the 404 template instead. | |
if ( ($using_template OR $parent_using_template == "tpl-protected.php") && !$user_has_perms ) { | |
// Modify the $wp_query object to interrupt the loop and set up for a 404 | |
global $wp_query; | |
$wp_query->set_404(); | |
// Set the HTTP status code to 404 | |
status_header( 404 ); | |
// Stop the user's browser from caching this request | |
nocache_headers(); | |
// Look for a 404 template to load | |
$four_oh_four = locate_template( ['404.php'] ); | |
// If it exists... | |
if ( '' != $four_oh_four ) { | |
// Return the 404 template | |
return $four_oh_four ; | |
// Otherwise... | |
} else { | |
// Return the homepage template | |
$front_page = locate_template( ['front-page.php'] ); | |
return $front_page; | |
} | |
} | |
// Standard behaviour applies otherwise | |
return $template; | |
} | |
add_filter( 'template_include', 'filter_protected_page', 99 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment