Forums

orderby=rand (5 posts)

  1. nerdynothings
    Member
    Posted 1 year ago #

    I have a featured post at the top of my site: http://nerdynothings.com

    I would like that post to be picked at random from the 10 most recent posts. Is this possible using "orderby=rand". Can i pass parameters to it, or is there another solution?

    Thanks!!

  2. vtxyzzy
    Member
    Posted 1 year ago #

    If you use 'orderby=rand', it overrides 'most recent', so that will not work. You can use get_col to select the IDs of the 10 most recent posts into an array. Then pick one of the 10 at random to retrieve for the featured post.

  3. nerdynothings
    Member
    Posted 1 year ago #

    that will absolutely work. but is far too advanced for me. I don't know how to set the parameters of the Database query, such as SELECT, FROM and WHERE...

  4. vtxyzzy
    Member
    Posted 1 year ago #

    Looks like you are using a custom theme, so I can't download it to look at the code. If you post your index.php file in the pastebin, I will look at it to see if I can give more specific directions.

  5. vtxyzzy
    Member
    Posted 1 year ago #

    Below is a code sample that selects a random post and echoes the title, date, and ID. You should replace the echo with the code from your template that displays the featured post.

    <?php
    // Select a random post from the x most recent posts
    $number_of_posts = 10;
    $sql = "SELECT ID FROM $wpdb->posts
       WHERE post_type = 'post'
          AND post_status = 'publish'
          AND post_date <= NOW()
       ORDER BY post_date DESC
       LIMIT 0,$number_of_posts";
    $ids = $wpdb->get_col($sql);
    $randid = $ids[rand(0,sizeof($ids) - 1)];
    $posts = get_posts("p=$randid");
    if ($posts) {
      $post = $posts[0];
      setup_postdata($post);
      // echo '<p>POST:';print_r($post);echo '</p>';
      echo "<p>RANDOM TITLE:".get_the_title() . "  DATE:$post->post_date  ID:$post->ID</p>";
    }
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic