I want to display products in random order within WooCommerce product categories, but the current code I am using only works for the shop page.
Here’s the code I have implemented:
// Shop random order. View settings drop down order by Woocommerce > Settings > Products > Display
add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );
function custom_woocommerce_get_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ( 'random_list' == $orderby_value ) {
$args['orderby'] = 'rand';
$args['order'] = '';
$args['meta_key'] = '';
}
return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
$sortby['random_list'] = 'Random';
return $sortby;
}
This successfully adds a "Random" option to the sorting dropdown and works on the shop page. However, it does not apply random sorting to product category pages.
I’ve tried adding additional hooks like pre_get_posts, but so far, nothing has worked.
How can I modify the code to ensure that products in category pages are displayed in random order by default, while still allowing other sorting options on the shop page?
2
Answers
You can set the default sorting to be "random", by using the
woocommerce_default_catalog_orderby
filter, and$default_orderby
parameter, as in this SO example.This filter allows you to override the default sorting option configured in WooCommerce settings and set a custom default sorting method.
You can add this extra piece of code to your existing code:
So your complete code would be:
This will set the default sorting to "Random" while still allowing other sorting options. Tested and works.