0

I use the following code to display a random post on a homepage:

<?php  global $query_string; query_posts($query_string . "&orderby=rand"); ?>

When the page is refresh posts positions are reversed. Is it possible to retain posts positions for a while? I want that posts positions are change once an hour.

1

You need to change the way you're querying for posts so that you can pass a seed value into MySQLs RAND function. If your posts are displayed within the same hour, that seed (and your post order) will remain unchanged.

This post shows an example. I've modified it to show how it might be done by the hour:

Try it with this in your theme functions.php file:

function hour_random_posts_orderby( $orderby ) {
    $seed = floor( time() / 3600 );
    $orderby = str_replace( 'RAND()', "RAND({$seed})", $orderby );
    return $orderby;
}

Now query for random posts like this:

<?php
$args = array(
    'orderby'        => 'rand'
);

add_filter( 'posts_orderby', 'hour_random_posts_orderby' );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        ....
    }
}
else {
    echo "<p>No posts found</p>";
    ....
}
....
wp_reset_postdata();
remove_filter( 'posts_orderby', 'hour_random_posts_orderby' );
?>
2
  • You should not be using query_posts, ever. Use pre_get_posts or WP_Query instead – Pieter Goosen Aug 3 '14 at 4:13
  • @PieterGoosen - Valid point. Updated my answer to use WP_query. – Dan Bough Aug 3 '14 at 12:10

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.