Home > database >  Serving a page to any URL that ends in its slug
Serving a page to any URL that ends in its slug

Time:03-16

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

Goal:

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:

​<?php

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);
           wp_redirect($redirect_url);
           exit;
        }
    }
}

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(){
    if(stristr($_SERVER['REQUEST_URI'],'403')){
        DO_SOMETHING
    }
}

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 isolate 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.

CodePudding user response:

Not sure if this is the olny issue but this line:

 if(!$user->ID == $author || !$user->ID == 1){

should be:

 if($user->ID !== $author || $user->ID !== 1){

CodePudding user response:

In order to prevent user from viewing any posts that he/she is not the author for, You should first get the post author ID, You can get the author ID of the post by adding the following few lines to single.php file in your current theme:

global $post,$current_user;
$author_id = $post->post_author;

if($current_user->ID != $author_id && !current_user_can('administrator')){
// Do whatever you want to do here
exit;
}

Note: The previous code checks if the user is not administrator and also not the author of the current post, You can use wp_safe_redirect(), or PHP header() function to redirect them anywhere else.

Thanks!

  • Related