# Show Comments Only After a Click

> Collapses the comments section behind a "Show comments" button, so long discussions do not distract from the article or load avatars until wanted.

- Type: PHP
- Runs: Frontend only
- Category: [Comments](https://wpide.com/library/category/comments/)
- Tags: comments, ux, performance
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/show-comments-on-click/

## Code

```php
// CSS selector of the comments section (classic themes use #comments, block themes .wp-block-comments).
$wpide_comments_selector = '#comments, .wp-block-comments';

add_action( 'wp_footer', function () use ( $wpide_comments_selector ) {
    if ( ! is_singular() || ! get_comments_number() ) {
        return;
    }

    $label = sprintf( 'Show comments (%s)', number_format_i18n( get_comments_number() ) );
    ?>
    <script>
    ( function () {
        var box = document.querySelector( <?php echo wp_json_encode( $wpide_comments_selector ); ?> );
        if ( ! box || /^#(comment|respond)/.test( window.location.hash ) ) {
            return;
        }
        var button = document.createElement( 'button' );
        button.type = 'button';
        button.className = 'wp-element-button wpide-show-comments';
        button.textContent = <?php echo wp_json_encode( $label ); ?>;
        button.setAttribute( 'aria-expanded', 'false' );
        box.hidden = true;
        box.parentNode.insertBefore( button, box );
        button.addEventListener( 'click', function () {
            box.hidden = false;
            button.remove();
        } );
    } )();
    </script>
    <?php
} );
```

## Notes

Links to a specific comment or to the form open the section automatically.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Show Comments Only After a Click" 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/
