This website uses cookies to personalize your experience. By using this website you agree to our cookie policy.

Randomize matched results?

Home Forums Product Support Forums Ajax Search Pro for WordPress Support Randomize matched results?

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #20611
    tavy87tavy87
    Participant

    Hi there,

    I have a set of custom fields for users that I use to do user searching. The search itself works, but it always returns the results in the same order. I’d like to randomize the results AFTER the search has been completed.

    I found the following support response but it doesn’t seem to do anything: https://wp-dreams.com/forums/topic/randomize-results/

    Any help would be appreciated, thank you!

    #20613
    tavy87tavy87
    Participant

    I decided to randomize my results in the following way, I think it works, and I hope it can help others!

    add_filter('asp_user_results', 'randomize_results', 10, 2);
    function randomize_results($user_results, $search_id) {
    	if ($search_id == 1) {
    		shuffle($user_results);
    	}
    	return $user_results;
    }
    #20615
    Ernest MarcinkoErnest Marcinko
    Keymaster

    Hi!

    This is the best possible way of doing it after the search process is completed, great job. The suggested solution on the linked topic is to randomize within the query, which I still do not recommend, and it may not even work in some cases.

    If I may suggest a tiny modification. The code above only affects user results, but it can be generalized to randomize everything returned, like so:

    add_filter('asp_results', 'asp_randomize_results', 10, 2);
    function asp_randomize_results($results, $search_id) {
      $affected_search_ids = array(1, 2, 3); // Search IDs to affect this code on
      
      // ---- DO NOT CHANGE BELOW -----  
      if ( in_array($search_id, $affected_search_ids) && count($results) > 0 ) {
          shuffle($results);
      }
      
      return $results;
    }

    Thank you again for sharing your solution, I really appreciate it!

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.