Support » Fixing WordPress » How do I show latest post from X random categories?

  • Hi,

    I am trying to display the latest post from 4 random categories on my homepage. I know how to do this by hard coding the categories or manually specifying which ones, but how would I go about randomizing which categories are displayed?


Viewing 1 replies (of 1 total)
  • I found the solution. The code below will do the trick:

    	// grab 4 random categories
    	$cats 		= '';
    	$categories	= get_categories();
    	$rand_keys 	= array_rand($categories, 4);
    	foreach ($rand_keys as $key) {
    		$cat = $categories[$key]->term_id;
    		$nam = $categories[$key]->cat_name;
    	// grab the latest post from each of the 4 random categories
    	$latest = new WP_Query("cat=$cat&amp;showposts=1"); 
    	while($latest->have_posts()) : $latest->the_post();
    <small>Latest in <a href="#"><?php echo $nam; ?></a></small>
    <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
    <?php the_excerpt(); ?>
    <?php endwhile; ?>
    <?php } ?>
Viewing 1 replies (of 1 total)
  • The topic ‘How do I show latest post from X random categories?’ is closed to new replies.