0

I have some code that runs on the client that checks every 30 seconds or so for new comments, and if a new comment is found the user is alerted.

The check count the comments on a page, and returns the count. The code that checks for comments is:

check_for_new_comments() {
$sitewide = get_option( 'sitewide_mode', 0 );   
$postID = $_POST['postID'];
$postID = ( $sitewide ) ? '' : $postID ;

$comments_number = get_comments( array( 'post_id' => $postID, 'status' => 'approve', 'type' => 'comment', 'count' => true ) );

$response = array( 'count' => $comments_number );wp_send_json( $response );

}

On the client, if the counter is greater than last time we checked then I call a function to get the comments missing using the following in jscript.

function( commentCheck ) {

if ( commentOld === null ) {    
    commentOld = commentResponse;
}

if ( commentOld.count < commentResponse.count ) {

    commentGrab();
    commentOld = commentResponse;

}

}

I know the count can be cached, but on dynamic sites with lots of comments (At busy ties I can get 1000 comments per post and around 100 visitors per minute putting a lot of strain on my server CPU). I think counting the comments might not be efficient and wonder if it would be more efficient to compare the tiestamp of the most recent comment.

Is "counting the number of comments and then comparing the count" quicker than "comparing the date of the most recent comment"? Can you please advise me on what is the more efficient approach and if it is to compared dates, how do I code this?

Many thanks

0

This is the most efficient way to count comments. That line of code can be simplified by using the get_comments_number template tag. Both of them simplify down to a simple SQL query that queries for "count". MySQL is highly optimized to count these records without scanning all of them.

0

At that volume it's likely that any Ajax request will be creating noticeable load on server, before even doing anything. Each Ajax request in WP has to do a complete core load and that's no light operation.

Unless your requirements change (such as reducing the volume of polling being done), you should probably start with looking into custom Ajax handlers, such as using SHORTINIT core load.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.