Support » Fixing WordPress » Random Posts in a Page?

  • Resolved greg9885


    I’m wondering how to display 4 random posts on a template page. I’ve seen a couple of other posts about this, but none seem to do what I want it to do. I’m not exactly sure how to get the loop to work in the page and I also want it to only randomly display the posts, not the pages. Do I have to use the query post function?

    Would this work (taken from another thread)?

    $rand_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY RAND() LIMIT 1");
    $my_query = new WP_Query("p=$rand_id");
Viewing 3 replies - 1 through 3 (of 3 total)
  • anybody have any ideas about this one?

    The code you have would only collect 1 random post.

    I’ll let you in on a secret I just learned (psst, tell everyone!): get_posts() can be used to collect and display any number of random posts you want. Here’s an example that lists the titles (as links) of four random posts:

    <ul><li><h2>Some Random Posts</h2>
    $rand_posts = get_posts('numberposts=4&orderby=RAND()');
    foreach( $rand_posts as $post ) :
    	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>

    Wow, that was EXTREMELY helpful!!!! Thank you soo much! And I will try to tell your secret to as many people as possible. I am having another problem with the title of the static posts page too. I have started a different thread, but no one seems to be biting. Any ideas for it?? THANK YOU again for your help.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Random Posts in a Page?’ is closed to new replies.