John Davidson

php - Serving a page to any URL that ends in its slug

0 comments
Message:


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.



My Answer:
php
function custom_post_type_redirect() {
global $post;

// Check if user is logged in
if (is_user_logged_in()) {
// Get current user ID
$current_user_id = get_current_user_id();

// Check if post is a custom post type
if (is_singular('your_custom_post_type')) {
// Get post author ID
$post_author_id = $post->post_author;

// Check if current user is not the post author
if ($current_user_id != $post_author_id) {
// Redirect to custom 403 page
wp_redirect(home_url('/403'));
exit;
}
}
}
}
add_action('template_redirect', 'custom_post_type_redirect');


Replace `'your_custom_post_type'` with the slug of your custom post type. This code will check if the current user is not the author of the custom post type and redirect them to a custom 403 page if they are not.

Rate this post

3 of 5 based on 4728 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us