Number of comments on archive view

Hello! What could be the best approach to get the number of comments on archive view (home page for example).

Right now you could count the comments using the _embedded.replies array.

const homeComments = state.source.get(state.router.link).items
  .filter(item => state.source.post[item.id]._embedded.replies)
  .reduce((acc, item) => acc + state.source.post[item.id]._embedded.replies[0].length, 0)

But it’s not going to be 100% reliable because replies only contains the first 10 comments.

Another way could be doing a new fetch to the comments endpoint with the ids of all the home posts, and looking at the "X-WP-Total" header. You can do a HEAD request to avoid downloading all the comments.

const homeIds = state.source.get(state.router.link).items.map(item => item.id).join(',');
const response = await fetch(`https://yourdomain.com/wp-json/wp/v2/comments?post=${homeIds}&per_page=100`, { method: "HEAD" });
const homeComments = response.headers.get("X-WP-Total");

Again, this will only contain 100 comments. If there’s more, you have to do an additional fetch:

fetch(`https://yourdomain.com/wp-json/wp/v2/comments?post=${homeIds}&per_page=100&page=2`, { method: "HEAD" });

WordPress will tell you if there’s an additional page with the "Link" header, rel="next".

I thought you wanted the sum of comments of all the posts of the homepage. My bad.

Then it’s simpler:

const comments = post._embedded.replies ? post._embedded.replies.length : 0;

If comments === 10 I would show a "+10" in the interface to show that there are 10 or more comments.