I need to restrict users without a specific capability from seeing a specific page. I can't use shortcodes or anything like that, I just want to redirect them if they get to that page URL.

I want to do this by adding something to my functions.php file... I would imagine the code would be something like...

// hook on_page_load() into wordpress page load
function on_page_load($current_page_ID) {
    if( $current_page_ID == 1234 && is_user_logged_in() &&
        current_user_can('do_something_special')) {
           return;  // allow it to continue
    } else {
           // otherwise
           die();   // or redirect or whatever

I can't quite figure out how to intercept each page load to see if they're going to the posts page. Can someone help? Or is there a more elegant way to accomplish this? Thanks.


If you want to redirect, a good event to use is template_redirect:

add_action( 'template_redirect', 'my_page_template_redirect' );
function my_page_template_redirect() {
    // You can skip is_user_logged_in() if checking the user capability
    if( is_page( 1234 ) && ! current_user_can( 'do_something_special' ) ) {
        $redirect_to = 'http://example.com/redirection-page';
        // Default code status for redirection using wp_redirect is 302
        // If you need a different status code check
        // https://codex.wordpress.org/Function_Reference/wp_redirect
        wp_redirect( esc_url_raw( $redirect_to ) );


You can find more information about template_redirect in the Codex.

As your question was about "how to intercept each page load", I think you should start reading these entries in the Codex:

  1. Plugin API
  2. Action definition and actions reference
  3. Filter definition and filters reference

Basically, actions are events that occur while WordPress processes a request. Each of them is appropiate to "intercept" the request and do actions. As they occur in different moments, you can choose the best action to use depending on what you need to do.

In this case about redirection when some page is requested and the user has some capibility assigned, template_redirect could be a very appropiate moment to intercept the request. According with the documentation of this action: "It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried".

|improve this answer|||||
  • 1
    I think the OP wanted to redirect users without the special capability. It looks like non-logged-in users can now view page 1234. – birgire Jan 18 '16 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.