Home / Comments / Auto-Collapse Long Comments
Duplicate Snippet

Embed Snippet on Your Site

Auto-Collapse Long Comments

Add a "Read More" button for long comments for better layouts.

50+
Code Preview
php
<?php
add_filter( 'comment_text', function( $comment_content ) {
	$max_length = 100; // Set the maximum length of the comment to display without collapsing
	if ( strlen( $comment_content ) > $max_length ) {
		$short_content = substr( $comment_content, 0, $max_length ) . '...';
		$full_content = esc_html( $comment_content );
		$comment_content = '<div class="collapsed-comment">' . esc_html( $short_content ) . ' <a href="#" class="read-more">Read more</a></div>';
		$comment_content .= '<div class="full-comment" style="display:none;">' . $full_content . ' <a href="#" class="read-less">Read less</a></div>';
	}
	return $comment_content;
} );
add_action('wp_footer', function() {
	echo '<script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            var readMoreLinks = document.querySelectorAll(".read-more");
            var readLessLinks = document.querySelectorAll(".read-less");
            readMoreLinks.forEach(function(link) {
                link.addEventListener("click", function(e) {
                    e.preventDefault();
                    link.parentElement.style.display = "none";
                    link.parentElement.nextElementSibling.style.display = "block";
                });
            });
            readLessLinks.forEach(function(link) {
                link.addEventListener("click", function(e) {
                    e.preventDefault();
                    link.parentElement.style.display = "none";
                    link.parentElement.previousElementSibling.style.display = "block";
                });
            });
        });
    </script>';
} );

Comments

Add a Comment