How to Display Random Products WooCommerce

random products woocommerceAre you looking for a way to showcase random WooCommerce products? If so, this post will present you with an easy-to-use random products WooCommerce code snippet that can be used in your plugin or WooCommerce theme development.

Ideally, to display random products in WooCommerce, you need to make use of the query and the loop like the ordinary WordPress post query and the loop.

First to display the random products you need to first create the query argument and do not forget to add the random option that helps to sort out the posts for you using a random order.

Random Products WooCommerce

The following is an example of a query argument that I will use in the example below that I will use to demonstrate how to show random products.

 

$args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'orderby' => 'rand',
);

This query pulls the posts from the WordPress database using random order by parameter. The next step involves looping through this data and displaying the random products on a page or using a shortcode. To display on-page, you can first create a custom page template that allows you to customize how the page looks as you display the products.

Display Random Products WooCommerce

To create a custom page template you can use the code below and the file should be in the base folder of your active WooCommerce theme or the Child theme.

 
/**
* Template Name: Testing Page
*
* @package WordPress
*/
get_header();

After creating the custom page template the next step involved looping through the data we queried in the step above so that we can display it.  The following is an example of the while loop you can use to loop through the data above and display it appropriately.

 

while ( $loop->have_posts() ) : $loop->the_post();

//Some code here to display the data

endwhile;

Now we can put together this code in one file as in the code below :

 

Conclusion

In this post, we have looked at how to create random products WooCommerce page that showcases the WooCommerce products as you can see in the demo above.

Similar Articles