I have several categories on my wp site.

On the front page I want to make sections for all of existing categories and than output 4 most recent articles from each of the category.

Is there a more elegant way of querying for those articles?

Currently I'm first getting all of existing categories :

get_terms('category', array('hide_empty' => 0)

Than I'm using foreach to loop through those categories and in each loop cycle I'm getting 4 articles from that category by using :

$articles = get_posts(array('numberposts' => 4, 'category' => $c->term_id));

And all of that is within my template file which I don't like.

Is this the recommended wordpress way, or is there more elegant solution?

I'm also bothered that by default, wordpress allready queries for most recent articles in advance on the homepage, so that query is kind of going to waste in my case.

2 Answers 2


Since the queries are not related to each other, there is no other way around it. You are going to end with with many queries and slow page (when it is not cached) on a site with many categories.

A better approch may be to show latest 50 posts, and display them by category, but it depends on what is it that you actually want to be displayed. If it is a news style page, then you will just have to apply some caching in order to get good performance.


No, you need the first piece of information to know what to retrieve for the second piece.

Also, if you're going to use get_posts, make sure to:

  • check the return value for errors
  • use 'supress_filters' => false so that it caches the results

Internally, get_posts() uses WP_Query which is what the main loop uses, so why not cut out the middle man?

Keep in mind that WordPress tries to cache things in WP_Cache. If you have a persistent object cache such as memcached or Redis installed and configured, you can use that to persist across page loads making things much faster. So if WordPress has already retrieved those posts, it won't cost as much

  • I'm actually mostly bothered with the fact that I'm doing my querying in view instead of controller.
    – Reygoch
    Commented Nov 1, 2016 at 15:04
  • 1
    Then grab the data in your controller beforehand, store it in the model, and pass the model to the view. Your question and what you're asking aren't the same and it appears to be a purely MVC question. There's no special MVC API WordPress has that you can plug in. I'm not even sure how that would work. Can you reword/edit your question so that it's a single well defined question that's crystal clear? It makes no mention of views and controllers, or that this is related to structure, it looks like a simple query question
    – Tom J Nowell
    Commented Nov 1, 2016 at 15:21

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.