Reputation: 139
I am trying to display products randomly on my shop page with this code:
add_filter('woocommerce_get_catalog_ordering_args', 'set_sort_order');
function set_sort_order($args) {
$args['orderby'] = 'rand';
return ($args);
}
But this code makes random product category page, but I need to just store page - front page. Not on product category page. How can I do it?
Upvotes: 2
Views: 2700
Reputation: 253814
Use the following instead to sort products randomly on shop archive pages only:
// Set default orderby query to "rand" option for shop archive pages
add_filter('woocommerce_get_catalog_ordering_args', 'shop_default_orderby_rand');
function shop_default_orderby_rand($args) {
if( is_shop() && ( ! isset($_GET['orderby']) || 'menu_order' === $_GET['orderby'] ) ) {
$args['orderby'] = 'rand';
return ($args);
}
}
Or you can also use this one too:
// Set default orderby query to "rand" for shop archive pages
add_action( 'pre_get_posts', 'shop_default_orderby_rand' );
function shop_default_orderby_rand( $query ) {
if ( is_shop() && ( ! isset($_GET['orderby']) || 'menu_order' === $_GET['orderby'] ) ) {
$query->set( 'orderby', 'rand' );
}
}
Insert the code in functions.php file of your active child theme (or active theme). Tested and works.
Upvotes: 4