Skip to main contentSkip to footer

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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

EmbedPress autoembeds

EmbedPress has an auto-embed feature that tries to embed all URLs found in posts. This can cause problems with Relevanssi: searches can take a very long time when EmbedPress tries to fetch all outside URLs. The solution is simple: you can disable this feature during Relevanssi excerpt creation. Add this…

OceanWP
OceanWP is a popular WordPress theme. It works fine with Relevanssi, but how it handles excerpts on the search results…

Related Posts:

Comment Section:

1 Comment. Leave new

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

    Reply

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed