WordPress Development Asked by sa eu on December 27, 2020
<a href="#" id="Link">Click me!</a>
<div id="lt">The text will get loaded here</div>
<script>
$("#Link").on("click", function(){
$("#lt").load("<?php comments_template(); ?>");
});
</script>
I asked this code to load the comments after clicking, but it does not work
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' );
Answered by cameronjonesweb on December 27, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP