WordPress Get Multiple Posts from Multiple Categories with one query

Using wordpress for a client (I wouldn’t over wise).

On their home page I want to get the latest 4 posts for each of 4 different categories, I then want to get 3 additional posts that are latest from any category and not currently used above, followed by 5 with the greatest number of page views in the last 2 weeks.

Read More

All this is easy but to use wordpress get_posts would require 6 different calls to the database, can this be done with one instead?

The Procedure:

  • Get 4 latest posts from the category NEWS
  • Get 4 latests posts from the category POLITICS that were not already fetched from the first four (there is a possibility that posts are in both categories)
  • Get 4 latest posts from category FEATURES that were not already fetched
  • Get 4 latest posts from category COMMENT … etc..
  • Get the 3 latest posts from any category that were not yet fetched
  • Get 5 posts with the greatest number of page views (stored in meta data under the name meta-page-views) that were not yet fetched

Is this possible without multiple queries.

Thanks,

Related posts

Leave a Reply

1 comment

  1. There is no way to do this in one call with usual wordpress functions. It might be possible with different categories in one query but you can’t have different sorting orders in one query.

    If you really really have to use one query, you could pull for example the latest 100 posts, store them in an array and then use PHP to sort and filter the result to your categories. However, this won’t work well with the page views. Also, a category that hasn’t been posted within the last 100 posts wouldn’t appear on your page.

    I don’t see a point in using one query only since it only creates problems. Even the most popular wordpress themes don’t do that.

    If your client is concerned about server load you should probably talk to them about caching.