Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

// 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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.