The following code shows how you can restrict some users from viewing a certain page. This could either be placed in a stand-alone plugin or the themes functions.php file. The code is fairly self-explanatory but I’ll walk through it.
First, pick an appropriate hook to use. I chose wp
because it’s after WordPress is fully loaded and the $wp
object is set up. You may want to hook in earlier or later depending on the application.
Next, determine if you’re on a page or post you want restricted to certain users. I chose to restrict posts/pages that have the post_title
of “Restricted”. You’ll have to use your own criteria. If the criteria is complicated, you’ll probably want to move the business logic to its own function. If the post isn’t restricted, then return early.
Next, check to see if the user should be able to see the page or post. The publish_posts
capability is one that neither logged-out, contributors, or subscribers have so I used that to see if they should be able to see the post. If they have that capability, then they can see the post, so return early.
Finally, redirect the users that shouldn’t be seeing the post by using wp_safe_redirect()
.
add_action( 'wp', 'restrict_contributors' );
function restrict_contributors() {
// * You'll have to determine how a post is restricted
if( 'Restricted' !== get_post()->post_title ) {
return;
}
//* Subscribers and contributors don't have the publish_posts capability
//* Non-logged in users also don't have this capability
if( current_user_can( 'publish_posts' ) ) {
return;
}
//* Redirect all other users to some location
wp_safe_redirect( home_url() );
exit;
}