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.
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.
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.
Sweet adapt Kevin 😉
Thanks Elliott, get_temp is the encouraged method. But I can see a number of uses for this snippet.