Skip to content

Commit fa24df9

Browse files
authored
REST API: Add persistent caching to Comments Count endpoint (#41545)
* Performance: Added caching to WPCOM API get comments endpoint. The WPCOM_JSON_API::wp_count_comments() did not have any caching mechanism. This caused noticable loads when many requests to this endpoint happen in a short period of time on WPCOM. This change adds a caching method similar to that used in core's get_comments() function. * Added changelog for WPCOM JSON API requests for comment counts change.
1 parent 27963df commit fa24df9

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Significance: patch
2+
Type: other
3+
4+
API: Added caching to JSON API requests for comments.

projects/plugins/jetpack/class.json-api.php

+26-14
Original file line numberDiff line numberDiff line change
@@ -1104,21 +1104,33 @@ public function wp_count_comments( $post_id ) {
11041104
return wp_count_comments( $post_id );
11051105
}
11061106

1107-
array_walk( $include, 'esc_sql' );
1108-
$where = sprintf(
1109-
"WHERE comment_type IN ( '%s' )",
1110-
implode( "','", $include )
1111-
);
1107+
// The following caching mechanism is based on what the get_comments() function uses.
11121108

1113-
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- `$where` is built with escaping just above.
1114-
$count = $wpdb->get_results(
1115-
"SELECT comment_approved, COUNT(*) AS num_comments
1116-
FROM $wpdb->comments
1117-
{$where}
1118-
GROUP BY comment_approved
1119-
"
1120-
);
1121-
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1109+
$key = md5( serialize( $include ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
1110+
$last_changed = wp_cache_get_last_changed( 'comment' );
1111+
1112+
$cache_key = "wp_count_comments:$key:$last_changed";
1113+
$count = wp_cache_get( $cache_key, 'jetpack-json-api' );
1114+
1115+
if ( false === $count ) {
1116+
array_walk( $include, 'esc_sql' );
1117+
$where = sprintf(
1118+
"WHERE comment_type IN ( '%s' )",
1119+
implode( "','", $include )
1120+
);
1121+
1122+
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- `$where` is built with escaping just above.
1123+
$count = $wpdb->get_results(
1124+
"SELECT comment_approved, COUNT(*) AS num_comments
1125+
FROM $wpdb->comments
1126+
{$where}
1127+
GROUP BY comment_approved
1128+
"
1129+
);
1130+
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1131+
1132+
wp_cache_add( $cache_key, $count, 'jetpack-json-api' );
1133+
}
11221134

11231135
$approved = array(
11241136
'0' => 'moderated',

0 commit comments

Comments
 (0)