Comments Load More. With Button or Infinity Scroll. No plugins used.

Please note, if you are looking for the feature how to publish comments in WordPress with AJAX, then please look at the other tutorial.

First of all let me show you what we will be creating. You can also download ready-to-use child TwentySeventeen theme with working ajax comments.

[videoloop mp4=”https://rudrastyh.com/wp-content/uploads/2018/01/wp-load-more-comments.mp4″ w=”1014″ h=”740″]

Before implementing any code or activating the child theme, please go to the Settings > Discussion and make sure that the checkbox is checked and last page is set to be displayed first.

WordPress break comments into pages for Load More button.
Go to Settings > Discussion, activate this checkbox and set the last page to be displayed first. But it doesn’t matter if you would like to display newer or older comments at the top of each page

Now you’re ready, let’s go!

Step 1. Add Loadmore button

Your first task is to find in your theme the comment pagination function paginate_comments_links() and replace it with the code below. If you can not find it, then place the code somewhere after <ol class="comment-list">...</ol> tag.


$cpage = get_query_var('cpage') ? get_query_var('cpage') : 1;

if( $cpage > 1 ) {
	echo '
More comments
'; }

Since the last comment page is displayed by default, $cpage is equal to the maxumim number of comment pages. The condition if( $cpage > 1 ) { means two things at the same time — print the load more button and the scripts if:

  1. there are 2 or more comment pages
  2. we are not on the first comment page, which will be displayed the last.

If you are looking to the wp_localize_script() direction, please do, but note that get_query_var('cpage') doesn’t work inside the wp_enqueue_scripts action hook. If you find the simple way to do it, I will appreciate a lot if you share your ideas in comments, if you have no idea what I’m talking about, a good wp_localize_script() example you can find here.

Step 2. Load More AJAX jQuery Script

In this step create an empty lolkekcheburek.js file and fill it with the code from below.


jQuery(function($){

	// load more button click event
	$('.misha_comment_loadmore').click( function(){
		var button = $(this);

		// decrease the current comment page value
		cpage--;

		$.ajax({
			url : ajaxurl, // AJAX handler, declared before
			data : {
				'action': 'cloadmore', // wp_ajax_cloadmore
				'post_id': parent_post_id, // the current post
				'cpage' : cpage, // current comment page
			},
			type : 'POST',
			beforeSend : function ( xhr ) {
				button.text('Loading...'); // preloader here
			},
			success : function( data ){
				if( data ) {
					$('ol.comment-list').append( data );
					button.text('More comments'); 
					 // if the last page, remove the button
					if ( cpage == 1 )
						button.remove();
				} else {
					button.remove();
				}
			}
		});
		return false;
	});

});

We decrease cpage value on line 8 because comment pages are displayed in descending order, we configured it in the beginning of this tutorial, remember?

Connect the lolkekcheburek.js file after jQuery library the way you want, but better with wp_enqueue_script action hook.

I didn’t plan to post this simple code but… Mmmmm… well.. πŸ˜€ This small piece of code will reduce the number of questions in comments at least 2x times. To your theme functions.php file:


add_action( 'wp_enqueue_scripts', 'for_those_who_have_no_idea_what_we_are_doing_here', 1 );

function for_those_who_have_no_idea_what_we_are_doing_here() {
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'lolkekcheburek', get_stylesheet_directory_uri() . '/lolkekcheburek.js', array('jquery') );

}

Once done, please click your button – does it change the text to “Loading…”? If yes, I suppose you did everything correctly. Congrats and let’s continue! πŸŽ‰

If not, please check your browser console, it is something with your jQuery code. And remember — your can always check the ready child theme.

Step 3. Retrieve the next comment page in PHP

Another code for your functions.php:


add_action('wp_ajax_cloadmore', 'misha_comments_loadmore_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_cloadmore', 'misha_comments_loadmore_handler'); // wp_ajax_nopriv_{action}

function misha_comments_loadmore_handler(){

	// maybe it isn't the best way to declare global $post variable, but it is simple and works perfectly!
	global $post;
	$post = get_post( $_POST['post_id'] );
	setup_postdata( $post );

	// actually we must copy the params from wp_list_comments() used in our theme
	wp_list_comments( array(
		'avatar_size' => 100,
		'page' => $_POST['cpage'], // current comment page
		'per_page' => get_option('comments_per_page'),
		'style' => 'ol', // comments won't wrapped in this tag and it is awesome!
		'short_ping' => true,
		'reply_text' => twentyseventeen_get_svg( array( 'icon' => 'mail-reply' ) ) . __( 'Reply', 'twentyseventeen' ),
	) );
	die; // don't forget this thing if you don't want "0" to be displayed
}

Bonus. Infinity Scrolling for Comments

I don’t recommend to use it because of a very simple reason — comment form is located under all comments. So, nobody could leave a comment until he scrolls down through all the comments. It seems ok, but what if there are 500 comments on this page?

In case you understand it but still want the infinity scroll just add this jQuery code:


jQuery(document).on('scroll', function() {
	var btn = jQuery('.misha_comment_loadmore');
	if( (jQuery(this).scrollTop() + jQuery(window).height() ) >= btn.offset().top){
		
		// check if the ajax request isn't in process right now
		if( button.text() == 'More comments' ) {
			button.trigger('click'); // click the button
		}

	}
});
Misha Rudrastyh

Misha Rudrastyh

I develop websites since 2008, so it is total of 13 years of experience, oh my gosh. Most of all I love love love to create websites with WordPress and Gutenberg, some ideas and thoughts I share throughout my blog.

Need some developer help? Contact me