I had a similar requirement where I should not let users access the author.php page based on the role a user was in. I register the template_redirect action to do my checks and redirect to 404 page even before the actual page is loaded.
Registration:
add_action( 'template_redirect', [ $this, 'handle_inactive_users']);
Handler:
public function handle_inactive_users() {
global $wp_query;
if ( $wp_query->is_author() ) {
$user = $wp_query->get_queried_object();
if ( is_a( $user, \WP_User::class ) && $user->has_cap( 'inactive' ) ) {
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();
}
}
}
If you chose to only use the following code snippet in the middle of template part, the page may have already been rendered partially and you are not actually redirected to a 404 page. So better to do it in the template_redirect
action -
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();