Posted on

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;
}

Add this function to your site and the search results will appear in random order. You can also do this:

add_filter( 'relevanssi_modify_wp_query', function ( $query ) {
  $query->set( 'orderby', 'rand' );
  return $query;
}

However, both of these solutions only work 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 a 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.

One comment Search results in random order

  1. 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.’)’;

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *