lazy load comments wordpress on click

Templates like the comments template need to be loaded on the page, as it relies on some global variables to know what post to load the comments for, so just pulling in the template with Javascript won’t work like that. You’ll need to create an AJAX wrapper that sets up the post data before getting the template.

Where you want your comments to go:

<div id="commentsTarget"><a href="#" id="loadComments">Click me!</a></div>

<script>
    jQuery( document ).ready( function() {
        jQuery( '#loadComments' ).click( function( e ) {
            e.preventDefault();
            jQuery.ajax({
                method: 'POST',
                url: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
                data: {
                    action: 'wpse380230_load_comments',
                    postID: '<?php echo get_the_ID(); ?>'
                },
                success: function( data ) {
                    jQuery( '#commentsTarget' ).html( data );
                }
            });
        });
    });
</script>

In your theme functions.php file:

function wpse380230_load_comments() {
    // Check to make sure the post ID has been sent through.
    if ( isset( $_POST['postID'] ) && ! empty( $_POST['postID'] ) ) {
        // Sanitise the post ID.
        $post_id = absint( wp_unslash( $_POST['postID'] ) );
        // Set up the nessecary global variables.
        global $post, $withcomments;
        $post         = get_post( $post_id );
        $withcomments = true;
        setup_postdata( $post );
        // Time to pull in the template :).
        comments_template();
    }
    wp_die();
}

add_action( 'wp_ajax_wpse380230_load_comments', 'wpse380230_load_comments' );
add_action( 'wp_ajax_nopriv_wpse380230_load_comments', 'wpse380230_load_comments' );

Leave a Comment