Still new to WordPress, so please go easy on me.


Prevent users of a specific role from viewing other custom post types made by users of same role.

Intended solution:

Modify the URL and redirect to a custom 403 page when the user ID doesn't match the post author. As such, if the person attempting to view example.com/%taxonomy%/%private-post-slug% would instead be redirected to example.com/%taxonomy%/403

Current redirect code:


add_action( 'template_redirect', 'private_posts_redirect');

function private_posts_redirect() {
    $user = wp_get_current_user();
    $post = get_post();
    $author = $post->post_author;
    if( get_post_type() == 'custom-post-type'){
        if(!$user->ID == $author || !$user->ID == 1){
           $intendedtarget = $_SERVER['REQUEST_URI'];
           $intendedtargetpath = parse_url( $intendedtarget, PHP_URL_PATH );
           $intendedtargetslug = pathinfo( $intendedtargetpath, PATHINFO_BASENAME );
           $redirectslug = '403';
           $redirecturl = str_replace( $intendedtargetslug, $redirectslug, $intendedtarget);

Current issue:

I've created a 403 page with '403' as the slug, I'm just not sure how to serve the content of that template page on any page that ends with that slug.

Tentative solution:

add_action('init' '403_page')

function 403_page(){

Edit: I know this only addresses the post author, I've already got the redirects for users that aren't of the role I'm looking to compartmentalize posts for. Additionally, I am using the Advanced Post Queries plugin to only serve authors their posts, however that doesn't prevent them from viewing others posts by typing random numbers into the URL and getting to view sensitive RFQ, quote, and pricing info that's unique to that user.

  • 1
    When you say that "I've created a 403 page with '403' as the slug" do you mean you've created a Page in the admin panel? If so, could you use get_permalink( 123 ) or home_url( '403' ) to wp_redirect() to that page? Otherwise, you'll need to create an endpoint of that slug. Here's an article by Metabox.io on creating an endpoint. Also see add_rewrite_endpoint().
    – Howdy_McGee
    Mar 16, 2022 at 4:20
  • Wish I could select a comment as an answer. This got everything working correctly. Thank you! Apr 15, 2022 at 4:16


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.