## php – Get the last 5 products from each category

Question

How can I select the last 5 products for each product category? I tried to select last 5 products from each category and add the tag “new”. I saw that is WP_QUERY, but I didn’t find a parameter that helps me. I have this code that works fine for add the tag “new” for products that is newer than 30 days. Thank you in advance, I really appreciate.

function display_new_loop_woocommerce() {
global $product;$datetime_now = new WC_DateTime();
$timestamp_now =$datetime_now->getTimestamp();

$args = array( 'post_type' => 'product', // your product post type 'posts_per_page' => - 1, );$posts = get_posts($args); foreach ($posts as $post): setup_postdata($post);

$product = new WC_Product($post->ID);

$datetime_created =$product->get_date_created();
$timestamp_created =$datetime_created->getTimestamp();

$time_delta =$timestamp_now - $timestamp_created;$sixty_days = 30 * 24 * 60 * 60;

if ( $time_delta <$sixty_days ) {
if( ! has_term( '', 'product_tag', $post->ID ) ) : wp_set_object_terms($post->ID, array('nou'), 'product_tag');
endif;
} else {
if( has_term( '', 'product_tag', $post->ID ) ) : wp_remove_object_terms($post->ID, array('nou'), 'product_tag');
endif;
}

wp_reset_postdata();
endforeach;
}

in progress 0
1 month 2021-09-17T02:52:40-05:00 0 Answer 0 views 0

1. 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.