A
A
Alexey2017-09-27 22:16:47
MySQL
Alexey, 2017-09-27 22:16:47

How to get comments for each post in the list?

Hello! I display a list of posts and I want to get the last 3 comments for each. How can this be done with less resources? Here's the principle:
59cbf902409dd165576237.jpeg
After all, if you get a list of posts, and then request from the database for each comment, then when you display 50 posts, you get an additional 50 queries to the database.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vorotnev, 2017-09-27
@HeadOnFire

1. Get posts (1 request if you don't pull and prime caches of metadata and taxonomies).
2. Pull out their IDs from the array of posts (wp_list_pluck or a similar method).
3. Get comments using WP_Comment_Query by passing the IDs from step 2 to the post__in property (1 request, if you do not pull and prime caches of metadata and posts)
4. Display posts in a cycle, in each iteration, take the necessary comments from the result of step 3
Total : 2 requests.
However, in real life, you still need metadata for both posts and comments. Therefore, there will be more requests, but not N + 1.
In general, it would not hurt to cache such things in their entirety, or at least the results of queries, in transients. For how long - depends on the frequency of updating information on the site. From 5 minutes to an hour.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question