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;
}