Do you want to add a touch of randomness to your WooCommerce store and showcase products in a unique way?
With a simple customization, you can implement a custom random products sorting filter that adds an exciting element to your online shop.
In this document, we’ll guide you through the process and provide a snippet code to achieve this.
Why Random Product Sorting?
While standard sorting options like popularity, price, or date are common, introducing a random sorting filter can bring an element of surprise to your customers’ shopping experience. This can be particularly engaging for visitors who enjoy discovering new products or are looking for inspiration.
How to Implement Custom Random Products Sorting Filter
To implement this feature, you’ll need to add a snippet of code to your child theme’s functions.php file. Here’s the code snippet for your convenience:
/**
Modify the product query to sort by random order
@param WP_Query $q The WP_Query instance.
/
function custom_random_products_sorting( $q ) {
if ( ! is_admin() && $q->is_main_query() && is_woocommerce() && is_shop() ) {
$q->set( 'orderby', 'rand' );
}
}
add_action( 'pre_get_posts', 'custom_random_products_sorting' );
This code hooks into the pre_get_posts action and modifies the product query to sort by random order when the main query is for the shop page in WooCommerce.
How to Add the Code to Your Child Theme
- Access your WordPress dashboard.
- Navigate to Appearance -> Theme Editor.
- Find and select your child theme’s functions.php file on the right-hand side.
- Copy and paste the provided code snippet at the end of the file.
- Save the changes by clicking Update File button.
Once you’ve added this customization, visit your WooCommerce shop page, and you’ll notice the products are now displayed in a random order. This simple modification can add a playful and dynamic aspect to your store, enticing customers to explore and discover new products.
We hope this document has been helpful. If you have any queries further, feel free to leave a comment below.