WordPress.org

Ready to get started?Download WordPress

Forums

How do I show latest post from X random categories? (2 posts)

  1. vossavant
    Member
    Posted 5 years ago #

    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?

    vossavant

  2. vossavant
    Member
    Posted 5 years ago #

    I found the solution. The code below will do the trick:

    <?php
    	// 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 } ?>

Topic Closed

This topic has been closed to new replies.

About this Topic