0

I want for my homepage to show 'x' latest posts from certain categories. The number of the posts returned depends on category. Either 10 or 15 posts/category. I want to use a single query to DB to ease the server load (returned posts will be approx 70). I'm thinking about a single WP_Query, selecting the category slugs and the max. no of posts_per_page. And then in the Loop I'll filter the results based on category name and limit by post counts. All post types are the default post. Am i on the right path here or is there a better approach? Any help appreciated.

7
  • Do you want to return 10/15 posts from each category?
    – Johansson
    Commented Jun 18, 2018 at 11:47
  • OK, so basically you're afraid of performance hit caused by multiple queries, so you want to select all posts and then loop through them? And what it there will be 200 posts per category? Commented Jun 18, 2018 at 15:01
  • @JackJohansson Yes that's the idea. The recent ones. Commented Jun 18, 2018 at 15:47
  • @KrzysiekDróżdż Maybe I didn't described it correctly. I don't want to select all posts. Just the last 15 of each category, but with a single or as few queries as possible. Commented Jun 18, 2018 at 15:48
  • You can't do that with a single WP_Query(). You can directly query posts using SELECT TOP SQL query, but that requires skill in writing and handling SQL queries.
    – Johansson
    Commented Jun 18, 2018 at 16:12

1 Answer 1

0

If you're running a website that has a high traffic, querying posts on each load will not be efficient. You should instead cache the data. Now, I'm not talking about a plugin that caches the pages, I'm talking about caching your query.

You can run 10 queries and fetch 10 post IDs from each category, and then form an array of post IDs and store them in the database, using a transient. This way, you can fetch the transient data and directly run a loop and output the post data.

1
  • Thank you all for your suggestions. I'll try the caching option. Commented Jun 18, 2018 at 18:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.