X

How to Restrict User Access to Specific Templates

Snippets by IsItWP

Are you looking for a way to restrict user access to a specific template on your WordPress theme or a new template created by you? While there’s probably a plugin for this, we have created a quick code snippet that you can use to restrict user access to specific templates in WordPress.

You’ll of course need to create a template file called error.php or the other option is to use something like wp_die('You don't have access.') instead of loading a template.

Instructions:

All you have to do is add this code to your theme’s index.php file:

<?php 
/* Template Name: Restricted to Authors only */
if ( !current_user_can('author')) {
	get_template_part('error');
	exit(0);
}
?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 50+ best WooCommerce themes and how to set up download tracking in WordPress with Google Analytics.

Comments  Leave a Reply

  1. What’s this for? Is this in the post-writing part of the back-end? Wouldn’t only Authors have access to template files already? Sorry if I’m missing something easy. Thanks.

    1.  Hi Cliff,  this would be on the front end for your theme but could be anything. I could setup a template that would let users post from the front end and use this to restrict access. Or this could simple display a list of users and I only let a specific people view it.

  2. Elliott the web design guy November 29, 2011 at 11:58 pm

    Sweet adapt Kevin 😉

    1. Thanks Elliott, get_temp is the encouraged method. But I can see a number of uses for this snippet.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!
[60% OFF Today!]
[60% OFF Today!]
[10% OFF Today!]
[10% OFF Today!]
[50% OFF Today!]
[50% OFF Today!]