a random blog post from the database (2 posts)

  1. willenglishiv
    Posted 3 years ago #

    so I know how to use WP_Query to get a random post (orderby => rand) but that only randomizes the order of blog posts retrieved from the database.

    How do I get a deeper randomization without increasing the posts_per_page number, and thusly bogging down the site?

  2. vtxyzzy
    Posted 3 years ago #

    Try this:

    $ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'post'
          AND post_status = 'publish'");
    $id_ndx = rand(0,count($ids)-1);
    $id = $ids[$id_ndx];
    $args = array(
       'post_in' => array($id)
    $results = new WP_Query($args);

Topic Closed

This topic has been closed to new replies.

About this Topic