[英]Display WooCommerce products randomly by default on shop page
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?我该怎么做?
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).在您的活动子主题(或活动主题)的functions.php 文件中插入代码。 Tested and works.测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.