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.
1 Answer
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.
-
Thank you all for your suggestions. I'll try the caching option. Commented Jun 18, 2018 at 18:36
WP_Query()
. You can directly query posts usingSELECT TOP
SQL query, but that requires skill in writing and handling SQL queries.