简体   繁体   中英

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). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM