Skip to content

Instantly share code, notes, and snippets.

@lokothodida
Last active February 7, 2019 12:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lokothodida/cf908e2901ec02ad9967 to your computer and use it in GitHub Desktop.
Save lokothodida/cf908e2901ec02ad9967 to your computer and use it in GitHub Desktop.
GetSimple tutorial on providing random search results for i18n search.

Ever wanted to have random items put into the search results pulled from I18N Search?

It's actually not that difficult. The technique hinges on the return_i18n_search_results function, specifically designed for doing custom results rendering.

We call the function with the desired paramters to get the results. To ensure a properly random selection, we'll set the maximum number of results to a high number (e.g. 999).

$search = return_i18n_search_results($tags, $words, 0, 999, $order, $lang);

Then we'll take the results themselves (which are saved as an array item with the key 'results') and shuffle them as many times as are desired.

shuffle($search['results']);

Finally, pull out the number of results desired from the shuffled list and loop through each result to output them as desired.

$search['results'] = array_slice($search['results'], 0, 5); // change 5 to whatever number you want
foreach ($search['results'] as $result) {
  // output  
}

Final Code

// total number of results
$total = 5;

// change parameters (except $max) to ones relevant to your search)
$search = return_i18n_search_results($tags=null, $words=null, $first=0, $max=999, $order=null, $lang=null);

// apply this function as many times as you want to throughly shuffle the results
shuffle($search['results']);

// now limit the results to the max number
$search['results'] = array_slice($search['results'], 0, $total);

// loop through each result and output as desired
foreach ($search['results'] as $result) {
  // output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment