Question

How can I restrict access to a specific Wordpress page based on the user's role or capability? I am aware that there are various plugins that can achieve this and I found some very aged solutions while googling.

I believe it is about time to have an uptodate solution that works.

Was it helpful?

Solution

As I tried to explain in the comments following my answer to a recent question of yours, and as referenced in the Dev Resources section at the bottom of your linked docs, current_user_can is (as far as I am aware) the most flexible and comprehensive way to test user capabilities given the replacement (2.0) and deprecation (3.0) of User Levels.

Whether you are permitting or restricting access to view a page or make specific changes, it makes sense to tie in with the capabilities already defined by Wordpress as associated with Roles. This becomes especially true when you use any sort of role scoping, capability editing, or super admin plugins or functions. It is also unhindered by applications in individual or multi-site installations, and covers the entire range of possible users.

When you test if the current user can do this or that, these capabilities are far less likely to change than which capabilities are associated with certain Roles or User Levels.

Everything you need to know about current_user_can is fairly well explained in the docs, and it generally follows this logic:

if ( current_user_can('do_something_pertaining_to_the_below') ) {
    echo 'You are a user who can do the above thing, so do the below thing';
    /* the thing */
}

Conversely:

if ( !current_user_can('some_fancy_capability') ) {
    echo 'No can do';
    return;
}
else { /* the similarly fancy, restricted thing */ }

All that said, if anyone has heard of a more progressive and intelligent way of doing it, I'm all ears!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top