Skip to content

Instantly share code, notes, and snippets.

@DrizzlyOwl
Created May 25, 2016 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrizzlyOwl/387eafeac23f798bec8b9b1c3a36dd17 to your computer and use it in GitHub Desktop.
Save DrizzlyOwl/387eafeac23f798bec8b9b1c3a36dd17 to your computer and use it in GitHub Desktop.
WordPress protected page template
<?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