Redirect Author Pages if Current User is Not The Author

Hello,
I currently have author pages and I want it so the public cannot access these pages but if the author is logged in they can access that page. Is there anyway to do this?

Thanks!

  • Ash

    Hello Nick

    Please try the following code:

    add_action( 'template_redirect', function() {
    	if( is_author() )
    	{
    		if( ! is_user_logged_in() )
    		{
    			wp_redirect( site_url() );
    			exit;
    		}
    
    		$user = wp_get_current_user();
    		if( strtolower( $user->roles[0] ) != 'author' )
    		{
    			wp_redirect( site_url() );
    			exit;
    		}
    	}
    } );

    You can use this code in your child theme's functions.php if the theme is not changed. Otherwise mu-plugin is the best option. To create a mu-plugin, go to wp-content/mu-plugins folder. If there is no mu-plugins folder then, create one. Now, inside the mu-plugins folder create file with name anything.php (make sure file extension is .php). Now start with a <?php tag and then put the above code.

    Hope it helps! Please feel free to ask more questions if you have any.

    Have a nice day!

    Cheers,
    Ash

  • Nick

    Hey Ash,

    That is kind of what I am looking for but its not working how I need it to. Heres probably a better explanation of what I am looking for:

    Right now I have this setup. There are author pages that have both a private and public feature. I want to it be setup like this basically removing the public author page.

    If current user is logged in and then they click on the link to go to the author page it goes to their page

    If they are logged out and they try to go to the author page it takes them to login page

    If they are logged in and try to view someone else's author page it just redirects them to their author page.

    Thanks,

  • Ash

    Hello Nick

    Please try the following:

    add_action( 'template_redirect', function() {
    	if( is_author() )
    	{
    		if( ! is_user_logged_in() )
    		{
    			wp_redirect( 'LOGIN PAGE URL GOES HERE' );
    			exit;
    		}
    
    		$author = get_queried_object();
    
    		if( $author->ID != get_current_user_id() )
    		{
    			wp_redirect( get_author_posts_url( get_current_user_id() ) );
    			exit;
    		}
    
    	}
    } );

    I didn't test the code though, but it should work. Let me know if it works for you.

    Have a nice day!

    Cheers,
    Ash