Wordpress:通过 ajax 获取评论数

Wordpress: get comments count via ajax

我正在使用 wpdiscuz 评论系统插件。 但我有一个麻烦:如果我添加评论,当然,我的 <?php comments_number( $zero, $one, $more ); ?> 没有更新。

我是 wordpress 的新手,我需要知道添加动态评论计数更新的最佳方式是什么?

例如每 30 秒检查一次评论计数,我可以用 jQuery 来写:没问题。

但是我如何在没有大量自定义代码的情况下通过 ajax 访问评论数?是真的吗?

在 WordPress 中使用 AJAX 非常简单,因为 WP 已经内置了处理 AJAX 请求的核心功能。 I had created tutorial on submitting form via AJAX in WP here。我相信在您的情况下,您不会提交表单,而只是想在服务器端重复请求某些操作,您将在其中 return 评论计数。

所以用 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文件中用setInterval或setTimeout重复调用ajax函数

这是一个简单的示例,要了解有关 ajax 在 WordPress 中的工作原理的更多信息,请阅读教程。

希望对您有所帮助!