Get woocommerce random products
Sometimes people asks me how to get N random products from Woocommerce plugin. Well, I heard it isn’t obvious or easy. And still I don’t know why. It is more than easy! We just need to use get_posts
function.
Simplest function to get N random products (default value is three as you may see in the source code) would look like that:
1 2 3 4 5 6 7 8 9 |
function my_wc_random_products( $count = 3 ) { $count = (int)$count; if ( $count < 1 ) { $count = 1; } return get_posts( [ 'posts_per_page' => $count, 'orderby' => 'rand', 'post_type' => 'product', ] ); } |