Search code examples
wordpress

Auto redirect to specific page if non author post


I need help with Wordpress, here's the idea:

  • I have a Custom Post Type called: History.
  • Posts are published publicly and are attributed to its own Author.

My goal:

  • From the front end, if another Author would try to access a link of one of the posts of which he's not the author then it redirects him to a specific page.
  • Except for Admin accounts.

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,


Solution

  • 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;
            }
        }
    }