I am using this function to redirect to a random post. I am trying to find a mechanism to prevent the same random post to appear twice in a row. Can anyone give a hint?
function sofa_view_random_post() {
// make array of all posts IDs
$q = get_posts('numberposts=-1');
$array = array();
foreach($q as $p) {
$array[] = $p->ID;
}
// randomize array to get random post
$k = array_rand($array);
$v = $array[$k];
wp_redirect( get_permalink( $v ) ); exit;
}
I get all posts IDs first and put them to array. I randomize the array to get a value. But not sure how to prevent same value from being triggered.
Store the previous result in the session, and make sure you don’t pick that one again:
I’m not sure how this applies to wordpress specifically, but it should be easily adaptable:
For completeness, here is the function incorporating the above code: