我使用wpdiscuz
插件的评论系统。但我有一个麻烦:如果我添加评论,当然,我的<?php comments_number( $zero, $one, $more ); ?>
没有更新。
我是新的wordpress,我需要知道,什么方式是最好的添加动态评论计数更新?
例如,每30秒检查一次评论计数,我可以用jQuery编写:没问题。
但是我怎么能访问评论计数通过ajax,没有大量的自定义代码?这是真的吗?
在WordPress中使用AJAX非常简单,因为WP已经内置了处理AJAX请求的核心功能。我在这里创建了通过AJAX在WP提交表单的教程。我相信在您的情况下,您不会提交表单,而只是想重复请求服务器端的某些操作,在那里您将返回评论计数。
用jQuery创建post ajax函数,如下所示:
var data = {
// ... some data
'action' => 'get_comments_count', // This data 'action' is required
}
// I specified relative path to wordpress ajax handler file,
// but better way would be specify in your template via function admin_url('admin-ajax.php')
// and getting it in js file
$.post('/wp-admin/admin-ajax.php', data, function(data) {
alert('This is data returned from the server ' + data);
}, 'json');
然后在你的functions.php中,像这样写:
add_action( 'wp_ajax_get_comments_count', 'get_comments_count' );
add_action( 'wp_ajax_nopriv_get_comments_count', 'get_comments_count' );
function get_comments_count() {
// A default response holder, which will have data for sending back to our js file
$response = array();
// ... Do fetching of comments count here, and store to $response
// Don't forget to exit at the end of processing
exit(json_encode($response));
}
然后在js文件中反复调用ajax函数setInterval或setTimeout。
这是一个快速的例子,要了解更多关于ajax在WordPress中的工作原理,请阅读教程。
希望有帮助!