Search results in random order

Do you want to order your search results in random order? Here’s how:

add_filter('relevanssi_hits_filter', 'shuffle_search');
function shuffle_search($hits) {
    shuffle($hits[0]);
    return $hits;
}

Put this code in your functions.php and the search results will appear in random order. However, this only works if all the search results are on the same page. If the results span multiple pages, they will be shuffled between page switches, and the second page can have results from the first page on it, and some posts may never appear in results.

Here’s a more complicated solution that solves the issue by setting the random number generator seed every hour. Searches within that hour will return the results in the same order. This means pagination will work (unless the searcher loads the first page on 00:59 and the second page on 01:00, in which case the results come from the different set).

add_filter('relevanssi_hits_filter', 'shuffle_search'); 
function shuffle_search($hits) { 
    $date = date("Ymdh"); 
    seeded_shuffle($hits[0], $date); 
    return $hits; 
}
 
function seeded_shuffle(&$items,$string) { 
    mt_srand(strlen($string)); 
    for ($i = count($items) - 1; $i > 0; $i--) { 
        $j = @mt_rand(0, $i); 
        $tmp = $items[$i]; 
        $items[$i] = $items[$j]; 
        $items[$j] = $tmp; 
    } 
}

The seeded shuffle function is from PHP documentation.

  • E Stahl

    How do I make this work for multiple search result pages. Currently each page reshuffles making so results show up twice and some not at all.
    I’ve seen this code that should work but I’m not sure how to include it in the function to make it work:

    if( !is_admin() ) {

    $seed = $_SESSION[‘seed’];

    if (empty($seed)) {

    $seed = rand();

    $_SESSION[‘seed’] = $seed;

    }

    $orderby_statement = ‘RAND(‘.$seed.’)’;