Usama Qasim
Usama Qasim

Reputation: 15

Restrict page access in wordpress based on the logged in user's email

I want to restrict a page on my wordpress website to user's that match the emails I have provided. If some other user or non-logged in users open the page the should receive a message that they do not have permission to view this page. Apart from the allowed users, admin should also be able to view the page. I have searched alot but there is no plugin that provide this functionality, only user role based restrictions are available. Any help is appreciated.

Upvotes: 0

Views: 2506

Answers (1)

Ozgur Sar
Ozgur Sar

Reputation: 2204

I suggest you to check users against their user role instead of their email addresses.

You can use built-it user roles of Wordpress such as editor or you can create your customrole with this code.

Example codes given below should go to your child theme's functions.php or you can install Code Snippets plugin to inject the custom functions to your WP site.

// Add custom role
add_role("customrole", __( "Custom Role" ),array('read' => true));

You can then assign users that you want to give access to certain pages by changing their roles.

I prefer to use a shortcode to restrict a page to a certain role or roles. You can use this code to create your custom shortcode. It will redirect users to 404 page who don't have access.

// Make a certain page available only to customrole users
function shortcode_restricted_page() {
    $current_user = wp_get_current_user();    
    $current_username = $current_user->user_login;
    $role = $current_user->roles[0];

    if ($role == 'customrole' || $role == 'administrator') {
        // Access granted to the page
        return;      
    }
    else {
        global $wp_query;
        $wp_query->set_404();
        status_header( 404 );
        get_template_part( 404 ); exit();
    }    
}
add_shortcode('restricted_page', 'shortcode_restricted_page');

You can now add [restricted_page]shotcode to any page's content to restrict that page easily.

Upvotes: 3

Related Questions