Show posts in random order from category loop

I have a category loop in WordPress that outputs different markup based on the category. This is all fine, now I need the posts to display in random order. I’ve used ‘orderby => “rand” but this only randomises the posts within each category, i.e. the categories themselves are still outputted in chronological order. I’m unsure what to do and would appreciate any help.

Code:

Read More
<?php

$categories = get_categories();
  foreach($categories as $category) {
  $args=array(
  'category__in' => array($category->term_id),
  'caller_get_posts'=>1,
  'orderby' => 'rand'
);
$posts=get_posts($args);
  shuffle($posts);
  if ($posts) {
    foreach($posts as $post) {
      setup_postdata($post); 
                   echo "<li class='cat-{$category->term_id}'><a href='".get_permalink()."'>".get_the_post_thumbnail()."</a></li><!-- 
                   -->";

    } 
  } 
} 
?>  

Update: Resolved withiEmanuele’s advice – adding shuffle( $categories );

Related posts

Leave a Reply

1 comment

  1. Use shuffle( $array ); to shuffle elements in array.

    $categories = get_categories();
    shuffle( $categories );
    
    foreach( $categories as $category ){
        //Your stuff
    }
    

    Hope it helps!