I've managed to sync the comments count on Site 2 in Wordpress multisite. If someone needs it, the code is below. Just make sure to set starting increment point of post ID's on another site to some high number. I've set it to 5 million, to avoid having duplicate post IDs on both sites.
It creates a custom REST API endpoint to intercept post updates coming from this extension. Then checks if the post ID exists on the main site. If don't, it means that the discussion is belonging to another site. Then proceeds to the posts table on the other site and updates it there.
Paste the code in your functions.php file and be sure to change "POST TABLE NAME ON SITE 2" to your own name (with prefix)
function custom_update_post(WP_REST_Request $request) {
$post_id = $request['id'];
$comment_count = $request['comment_count'];
if (get_post($post_id) !== null) {
// Update the existing post with the new comment count
wp_update_post(array(
'ID' => $post_id,
'comment_count' => $comment_count
));
} else {
// Update the second site on multisite table with the new comment count
global $wpdb;
$table_name = 'POST TABLE NAME ON SITE 2';
$existing_record = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $post_id));
if ($existing_record) {
$wpdb->update(
$table_name,
array('comment_count' => $comment_count),
array('ID' => $post_id),
array('%d'),
array('%d')
);
} else {
$wpdb->insert(
$table_name,
array(
'ID' => $post_id,
'comment_count' => $comment_count
),
array('%d', '%d')
);
}
}
return new WP_REST_Response("Comment count updated successfully", 200);
}
function custom_update_post_register_route() {
register_rest_route('wp/v2', '/posts/(?P<id>\d+)', array(
'methods' => 'POST',
'callback' => 'custom_update_post',
'permission_callback' => function () {
return current_user_can('edit_posts');
},
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric($param);
}
),
'comment_count' => array(
'required' => true,
'validate_callback' => function($param, $request, $key) {
return is_numeric($param);
}
),
),
));
}
add_action('rest_api_init', 'custom_update_post_register_route');