questions

Display random category woocommerce – Home page

Rate this post

In my eshop (woocommerce), i have 10 categories. i display on my home page only 4 (random method) with a button ‘see more’.

But the 4 categories are still the same (last categories).

I would like to display 4 categories among the 10 and not the last 4.

My code :

<?php 
$prod_categories = get_terms( 'product_cat', array(
'number'       => 4,
'exclude'      => array( 23 ),
'hide_empty'   => false,
));
shuffle( $prod_categories );
foreach( $prod_categories as $prod_cat ) :
$cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
$shop_catalog_img = wp_get_attachment_image_src( $cat_thumb_id, $size = 'large' );
$term_link = get_term_link( $prod_cat, 'product_cat' );
?>
<div class="col-md-3">
<a href="<?php echo $term_link; ?>"><img src="<?php echo $shop_catalog_img[0]; ?>" alt="<?php echo $prod_cat->name; ?>" /><h2><?php echo $prod_cat->name; ?></h2></a>
</div>
<?php endforeach; wp_reset_query(); ?>

Any suggestion ?

 

✔️Solution:

it works with this code.

remove this line

'number'       => 4,

and add below shuffle, this line

$prod_categories= array_slice( $prod_categories, 0, 4 );

<?php 
$prod_categories = get_terms( 'product_cat', array(
'exclude'      => array( 23 ),
'hide_empty'   => false,
));
shuffle( $prod_categories );
$prod_categories= array_slice( $prod_categories, 0, 4 );
foreach( $prod_categories as $prod_cat ) :
$cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
$shop_catalog_img = wp_get_attachment_image_src( $cat_thumb_id, $size = 'large' );
$term_link = get_term_link( $prod_cat, 'product_cat' );
?>
<div class="col-md-3">
<a href="<?php echo $term_link; ?>"><img src="<?php echo $shop_catalog_img[0]; ?>" alt="<?php echo $prod_cat->name; ?>" /><h2><?php echo $prod_cat->name; ?></h2></a>
</div>
<?php endforeach; wp_reset_query(); ?>

Leave a Reply

Your email address will not be published.

Back to top button