Skip to content

Instantly share code, notes, and snippets.

@growdev
Created September 16, 2015 23:35
Show Gist options
  • Save growdev/71f2bf8182969dbc6e71 to your computer and use it in GitHub Desktop.
Save growdev/71f2bf8182969dbc6e71 to your computer and use it in GitHub Desktop.
WooCommerce Get random Products
<?php
add_shortcode( 'random_products', 'growdev_random_products' );
function growdev_random_products( ) {
$meta_query = WC()->query->get_meta_query();
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => '12',
'orderby' => 'rand',
'meta_query' => $meta_query
);
ob_start();
$products = new WP_Query( $args );
$columns = '4';
$woocommerce_loop['columns'] = $columns;
if ( $products->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
wp_reset_postdata();
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
}
@tomifin
Copy link

tomifin commented May 22, 2017

hi, can this be edited to get only random products that are featured? Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment