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.
Opens WPIDE on
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
- 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.