<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>
我要求此代码在单击后加载注释,但它不起作用延迟加载评论WordPress点击
1 个回复
SO网友:cameronjonesweb
像comments模板这样的模板需要加载到页面上,因为它依赖于一些全局变量来知道加载评论的目的是什么帖子,所以仅使用Javascript拉入模板不会像这样工作。在获取模板之前,需要创建一个AJAX包装器来设置post数据。
您希望您的评论去哪里:
<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>
在您的主题中functions.php
文件: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\' );