WooCommerce: Get newest products and sort them (partially) randomly

Viewed 119

I want to get the last 20 posts (in my case WooCommerce products) and show 10 of them in a random order.

For now I get the new posts like this:

$args = array(
    'post_type'                     => 'product',
    'orderby'                       => 'date',
    'order'                         => 'DESC',
    'posts_per_page'                => 20,
);

I know that I could get the posts in random order like this:

'orderby'                       => 'rand',
'posts_per_page'                => 10,

But how is it possible to combine these two? w Is there a way to store the posts from the first loop and use them in a second loop?

1 Answers

There are several ways to do this, this is one of them

$recent_posts = wp_get_recent_posts( array(
    'numberposts' => 20, // Number of recent posts
    'post_status' => 'publish', // Show only the published posts
    'post_type'   => 'product'
));

// array_splice ( array, offset, length )
$sub = array_splice( $recent_posts, 10, 10 );

// Random
shuffle( $sub );

array_splice( $recent_posts, 10, 0, $sub );

// Loop
foreach( $recent_posts as $post ) {
    echo $post['ID'] . '<br>';
    //echo '<pre>', print_r( $post, 1), '</pre>';
}

wp_reset_query();
Related