• All of my products belong to one of two top level product categories (A and B). I need to group product search results into buckets by these two product categories and display the buckets with labels. like this:

    Category A

    search results

    Category B

    search results

    I understand the key is on this page: https://www.relevanssi.com/user-manual/filter-hooks/relevanssi_hits_filter/ but I don’t know enough PHP to make it work.
    Would anyone be kind enough to post an example of the code required to make this work?

    Thank you in advance!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Mikko Saari

    (@msaari)

    Yes, that’s the trick; the method is described under the heading “Sorting” on the mentioned page. On top of that, you also need to modify your search results template to display the buckets separately.

    add_filter( 'relevanssi_hits_filter', 'product_cat_buckets' );
    function product_cat_buckets( $hits ) {
      $bucket_a = array();
      $bucket_b = array();
      foreach ( $hits[0] as $_post ) {
        $post_object = relevanssi_get_an_object( $_post )['object'];    
        if ( has_term( 'category_a', 'product_cat', $post_object ) ) {
          $bucket_a[] = $_post;
        } else {
          $bucket_b[] = $_post;
        }
      }
      $hits[0] = array_merge( $bucket_a, $bucket_b );
      return $hits;
    }

    This code will do the sorting. Just replace category_a with the name of the Category A. The code on your search results template depends on your theme.

    Thread Starter jlstysis

    (@jlstysis)

    Thank you very much!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Group Search Results by Category’ is closed to new replies.