WordPress / Discourse API Strategy: Get Reply Count via API Efficiently


#1

Hi all,

I’m going to use a hybrid of WP-Discourse + Embedded Comments via JS on our blog.

I’d like to show the number of replies / comments each post has, at least within the single post (single.php), but don’t want to slam the Discourse API 10,000+ times per day or slow the blog down while it retrieves that.

Does anyone have any good strategies for getting and saving the reply_count so that we don’t hit the server too often, or slow the blog from loading too often?

Are there good methods of “caching” the reply_count in post_meta / custom fields, and only updating it if it’s requested and the cache date is X hours old?

Or perhaps a cron job that just goes through all posts and updates regularly without slowing down the site ever?

Any other ideas? This is more of a WordPress strategy than anything.

Thanks!!


(Marko Kaartinen) #2

WordPress has transients for caching data.

https://codex.wordpress.org/Transients_API


(Simon Cossar) #3

If you publish the posts through WP Discourse and setup the ‘Sync Comment Data’ webhook, it will store the Discourse comments count as post meta data with the key discourse_comments_count. If you’re not using the WP Discourse comments template for displaying the comments, you’ll need to write a function that hooks into the WordPress get_comments_number filter and returns the discourse_comments_count value.

You can do this without setting up a webhook. It’s a lot more efficient with it though.

Edit: the Sync Comment Data webhook only updates the comment numbers and tells the WP Discourse plugin to update the comment content the next time the page is displayed, so using it to update the comment numbers when the WP Discourse comments template isn’t being used should be quite efficient. You can see the logic of it here: wp-discourse/discourse-webhook-refresh.php at master · discourse/wp-discourse · GitHub.