Wordpress: Random category page posts?

Status
Not open for further replies.

nachoninja

Love the dog
Oct 3, 2006
4,041
49
0
Fleshlightville
How does one get random posts for each category page?

ie. domain.com/?cat=4 so random posts show for only category 4, and so on for every other category page.

I've seen a few coding options but none that do random posts for the specific category page you are on.....

my archive.php page:

Code:
<?php get_header(); ?>

<div id="content">

    <div id="contentleft">
<h4><?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' Category'; } ?> </h4>




                <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <h1><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h1>
         <?php the_excerpt(); ?><div style="clear:both;"></div>
        <div class="clearfloat border_bottom"></div>
        <?php endwhile; else: ?>
        
        <p><?php _e('Sorry, no posts matched your criteria.'); ?></p><?php endif; ?>
        <p><?php posts_nav_link(' — ', __('« Previous Page'), __('Next Page »')); ?></p>


    </div>
    
<?php include(TEMPLATEPATH."/sidebar_post.php");?>
        
</div>

<!-- The main column ends  -->

<?php get_footer(); ?>
 


Take the default WP loop

Code:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

and replace it with a new loop object (which offers more options), like so:

<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; //set this var for pagination
$mynewquery = new WP_Query('orderby=rand&paged='.$paged); //construct query object. the 'orderby=rand' randomizes the query

if($mynewquery->have_posts()) : while($mynewquery->have_posts()) : $mynewquery->the_post(); //the actual WP loop you are replacing
?>

This should work but it will randomize every type of archive (tags and time archives too). If you only want the categories to display random posts, you could do this before building the object:

if(is_category()) $ordering = 'rand'; else $ordering = 'modified';
...and then replacing the 'rand' with $ordering when you build the object. I hope this makes sense.
 
  • Like
Reactions: nachoninja
The function supported by Wordpress Codex looks like this:

<ul><li><h2>A random selection of my writing</h2>
<ul>
<?php
$rand_posts = get_posts('numberposts=5&orderby=rand');
foreach( $rand_posts as $post ) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
</li></ul>
If you want also other template tags like the_content or the_tags you can put it inside :)
 
Status
Not open for further replies.