1

I'd like to know how to order by "random" instead of by "date".

Can someone help me modify this so it gets posts randomly instead of by date?

$posts = get_posts('numberposts=5&orderby=date&fields=all&tag='.$tag);

Thank you!

3 Answers 3

2
$randomPosts = get_posts(array(
   'orderby' => 'rand',
   'posts_per_page' => 5,
   'tag' => $tag,
));

Take a gander at the WP_Query documentation. get_posts uses WP_Query under the hood, so you can use any arguments that may be used there.

0

you can use rand as orderby check below code

 $args = array(
         'posts_per_page'   => 5,
         'offset'           => 0,
         'category'         => '',
         'category_name'    => '',
         'orderby'          => 'post_date',
         'order'            => 'rand',
         'include'          => '',
         'exclude'          => '',
         'meta_key'         => '',
         'meta_value'       => '',
         'post_type'        => 'post',
         'post_mime_type'   => '',
         'post_parent'      => '',
         'post_status'      => 'publish',
         'suppress_filters' => true 
); 

$myposts = get_posts( $args );
0

Use the following code:

<li><h2>Random Post</h2>
<ul>
<?php $posts = get_posts('orderby=rand&numberposts=5'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</li>
<?php } ?>
</ul>
</li>

You can customize the styling around it. If you want to display more than 5 posts, simply change the number 5 to the number of your choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.