Show Comments Only to Logged-In Users
Hides existing comments and the comment form from visitors who are not logged in, including in feeds and the REST API, and invites them to log in.
Opens WPIDE on
Code
$wpide_guest = function () {
return ! is_user_logged_in() && ! is_admin();
};
add_filter( 'comments_array', function ( $comments ) use ( $wpide_guest ) {
return $wpide_guest() ? array() : $comments;
}, 20 );
add_filter( 'get_comments_number', function ( $count ) use ( $wpide_guest ) {
return $wpide_guest() ? 0 : $count;
}, 20 );
add_filter( 'comments_open', function ( $open ) use ( $wpide_guest ) {
return $wpide_guest() ? false : $open;
}, 20 );
add_filter( 'comment_feed_where', function ( $where ) use ( $wpide_guest ) {
return $wpide_guest() ? $where . ' AND 1=0' : $where;
} );
add_filter( 'rest_endpoints', function ( $endpoints ) {
if ( ! is_user_logged_in() ) {
foreach ( array_keys( $endpoints ) as $route ) {
if ( 0 === strpos( $route, '/wp/v2/comments' ) ) {
unset( $endpoints[ $route ] );
}
}
}
return $endpoints;
} );
add_filter( 'the_content', function ( $content ) use ( $wpide_guest ) {
if ( ! $wpide_guest() || ! is_singular() || ! in_the_loop() || ! is_main_query() || ! post_type_supports( get_post_type(), 'comments' ) ) {
return $content;
}
return $content . sprintf( '<p class="wpide-comments-login"><a href="%s">Log in</a> to read and join the discussion.</p>', esc_url( wp_login_url( get_permalink() ) ) );
}, 20 );
Notes
Logged-in users of any role see and post comments as usual.
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.