Get the last 5 products from each category

You have to ways to achieve this I guess. The one that you pick depends on how many products and how many categories are present in your website.


If you have an huge amount of products but not so many categories, then probably the best approach is to get the categories first:

$product_categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] );

and then iterate over them to get the most recent products for each category with a new query for each category.


On the other hand, if you have many categories, this would lead to many queries performed.

It this case you could think to get all the products as you already do, iterate over them and for each post:

  1. Get all the categories IDs: $product->get_category_ids()
  2. Build a multidimensional array that has categories IDs as first set of keys, and product timestamp as second set of keys.

It will be something like this:

[
  5 => [
    '123456789' => $product1
    '123456877' => $product2
    ...
  ],
  10 => [
    '123456888' => $product3
    ...
  ]
]

Then you can sort the array by second set of keys and get the first 5 elements of each nested array.


NOTE: In any case, whatever you choice, if you have a good amount of products and/or categories, this would not be a quick operation, so I’d suggest you to use WP Transients to store the IDs that you retrieve, and keep them saved until you add a new product, remove an existing product or change the category of an existing product (and maybe invalidate after a fixed amount of time, just to be sure).