# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Comments](https://wpide.com/library/category/comments/)
- Tags: comments, members, privacy
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/comments-for-logged-in-only/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Show Comments Only to Logged-In Users" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
