Saturday, 7 September 2013

Show posts in random order from category loop

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:
<?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><!--
-->";
}
}
}
?>

No comments:

Post a Comment