WooCommerce - Show Random Products
Alright folks here is a bit of code I am using for mine its for recent products but is doing the job. Just add to page you want to show them on.
[recent_products per_page="4" columns="4" orderby="rand" order="rand"]
Try this. Paste code into functions.php Go to wp-admin/ Woocommerce > Settings > Products > Display View settings drop down order by random will be a new option. *note: it will be the the last option.
// 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'] ) ? woocommerce_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 works for me:
<?php
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'post_type' => 'product' );
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata();
?>