I need help with Wordpress, here's the idea:
My goal:
This code is Working Well, but what if i want to Exclude Admin or Editor Role ? :)
add_action( 'get_header', 'wpso_author_redirection' );
function wpso_author_redirection() {
if ( is_single() ) {
$current_post_details = get_post( get_the_ID(), ARRAY_A );
$user_id = get_current_user_id();
if ( $user_id !== absint( $current_post_details['post_author'] ) ) {
wp_redirect( home_url() );
}
}
}
Regards,
You will need to get user object instead of ID to get more info about the user.
add_action( 'get_header', 'wpso_author_redirection' );
function wpso_author_redirection() {
if ( is_single() ) {
$user = wp_get_current_user();
$user_id = $user->ID;
// Skip redirection for 'Administrator' or 'Editor'
if ( array_intersect( ['administrator', 'editor'], $user->roles ) ) {
return; // Allow access
}
// Redirect if the user is not the post author
$post_author = (int) get_post_field( 'post_author', get_the_ID() );
if ( $user_id !== $post_author ) {
wp_redirect( home_url() );
exit;
}
}
}