byCoder
byCoder

Reputation: 9184

Wordpress: get comments count via ajax

I'm using wpdiscuz plugin for comment-system. But i have one trouble: if i add a comment, sure, that my <?php comments_number( $zero, $one, $more ); ?> is not updated.

I'm new to wordpress, and i need to know, what way is the best for adding dynamical comments count update?

For example checking comments count every 30sec, i can write it with jQuery: no problem.

But how can i access comments count via ajax, without huge amount of custom code? Is it real?

Upvotes: 0

Views: 977

Answers (1)

Dan Mironis
Dan Mironis

Reputation: 721

Using AJAX in WordPress is pretty easy, because WP has already built-in core functionality for handling AJAX requests. I had created tutorial on submitting form via AJAX in WP here. I believe that in your situation you would not submit form, but just want to repeatedly request to some action in server-side, where you will return comments count.

So create post ajax function with jQuery like this:

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');

Then in you functions.php, wrtie something like this:

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));
}

And then repeatedly call ajax function in js file with setInterval or setTimeout.

This is a quick example, to understand more on how ajax in WordPress works, read the tutorial.

Hope it helps!

Upvotes: 1

Related Questions