How to redirect users without permission to view content to a custom page?

I want users who don't have permission to view content to be redirected to a page when they are presented with the default "Nothing Found" page. I've already redirected 404s but this is not exactly a 404. The content exists, they just don't have permission to view it.

Topic redirect permissions Wordpress

Category Web


You should hook into template_redirect. Add the following into your functions.php.

template_redirect is the last hook that is loaded before any HTML content is output. Once HTML is output, wp_redirect will generate errors.

You did not mention how you were verifying permissions for the users but I presume you have this in hand.

function redirect_users()    {
    if( is_admin() )
        return;

    if( !$permission )    {
        wp_redirect( 'http://pagetoredirectto.com' );
        exit;
    }
}
add_action( 'template_redirect', 'redirect_users' );

Codex: wp_redirect

Codex: template_redirect


Redirects and forced 404 are not that good for SEO, also might hurt user experience.

I recommend that you take this approach (if you're code savvy):

<?php
//Your page template

//Check if user have permission
if ( $permission ) {

     //All your page/post content here
}

//Else user have no permission -> show him something else like notice
else {

    ?>
    <h1>You don't have permission to see that page.</h1>
    <a href="//www.site.com/buy-access/">Press here to buy access!</a>

    <?php

    //Or whatever your page / bussiness model is
} ?>

Let me know if that's approach works for you.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.