lazy load comments wordpress on click

 <a href="#" id="Link">Click me!</a>
    <div id="lt">The text will get loaded here</div>
      $("#Link").on("click", function(){
        $("#lt").load("<?php comments_template(); ?>");

I asked this code to load the comments after clicking, but it does not work

WordPress Development Asked by sa eu on December 27, 2020

1 Answers

One Answer

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>

    jQuery( document ).ready( function() {
        jQuery( '#loadComments' ).click( function( e ) {
                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 );

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 :).

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

Answered by cameronjonesweb on December 27, 2020

Add your own answers!

Related Questions

Plugin updates are not shown

1  Asked on December 24, 2021


WordPress Customizer Help with FontAwesome Icon

2  Asked on December 24, 2021 by ashiquzzaman-kiron


Move users and passwords from one wordpress site to another

3  Asked on December 24, 2021 by user106747


adding fade on mouseover to images

2  Asked on December 24, 2021 by baksudin


Get post terms with hierarchical relationships

1  Asked on December 22, 2021 by mikkelbreum


All links redirecting to homepage

1  Asked on December 22, 2021 by thebeardedguy


Simple Local Avatar Plugin

1  Asked on December 19, 2021 by user34634


Disable plugins on cron and ajax page

1  Asked on December 19, 2021 by humpty


Ask a Question

Get help from others!

© 2022 All rights reserved.