How to fix slow comment query?

My site has a very modified version of the WP Unread Comments plugin. The widget displays a list of posts with unread comments in the sidebar. My issue is that the database query that generates the list of comments is very slow and I don’t know how to fix it.

I think that the problem is in the following segment of code. The main change that I made here to the original plugin code was to add the date_query parameter.

$comments = get_comments( array(
‘number’ => $number,
‘order’ => $order,
‘status’ => ‘approve’,
‘post_status’ => ‘publish’,
‘date_query’ => array(
array(‘after’ => ‘2 weeks ago’,))
) );

$output .= $args[‘before_widget’];
if ( $title ) {
$output .= $args[‘before_title’] . $title . $args[‘after_title’];
$output .= ‘<ul id=”recentcomments”>’;

$number = $instance[‘number_unread’];

The site currently has about 130,000 comments. I recently deleted comments older than 2 years. This removed about 300,000 comments and the Unread Comments plugin started working faster. The time shown by Query Monitor was cut by two-thirds.

In short, I think the solution may involve limiting how much of the comments database is read by the query. I thought that’s what I was doing when I added the date_query parameter. Any tips on how I can make the code more efficient would be super welcome!

Read more here:: How to fix slow comment query?

Leave a Reply

Your email address will not be published. Required fields are marked *