404 for Author Pages of Users Without Posts
Returns a 404 for the author archive of anyone who has never published, such as subscribers and customers, so their usernames and empty profile pages are not exposed.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
global $wp_query;
if ( ! is_author() ) {
return;
}
$user = get_queried_object();
if ( ! $user instanceof WP_User ) {
return;
}
// Users who never published anything (subscribers, customers, new staff) get no public profile page.
$types = array_values( get_post_types( array( 'public' => true ) ) );
if ( count_user_posts( $user->ID, $types, true ) > 0 ) {
return;
}
$wp_query->set_404();
status_header( 404 );
nocache_headers();
}, 1 );
Notes
Authors get their archive back as soon as they publish something.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.