• hello, I ran into a problem and had to use custom fields in the form of “sku” for woocommerce products, but relevanssi does not give exact matches. how can I fix this?

    • This topic was modified 4 years, 12 months ago by kudiluv.
Viewing 6 replies - 1 through 6 (of 6 total)
  • Plugin Author Mikko Saari

    (@msaari)

    Let’s see if I can understand. Tell me if I go wrong at some point:

    1. Usually WooCommerce has the SKU in the custom field _sku. For some reason, on your site, the custom field is named sku.

    2. You’ve set Relevanssi to index the custom field sku and have rebuilt the index after that.

    3. The search is still not finding posts when you search for the SKU.

    Is that right?

    Thread Starter kudiluv

    (@kudiluv)

    The search finds products, but this is a list and the desired product may be at the end of the list. It is necessary that there is a specific match.

    Plugin Author Mikko Saari

    (@msaari)

    Try adding this to your theme functions.php:

    add_filter( 'relevanssi_results', 'rlv_exact_boost' );
    function rlv_exact_boost( $results ) {
      $query = strtolower( get_search_query() );
      foreach ( $results as $post_id => $weight ) {
        $post = relevanssi_get_post( $post_id );
        if ( get_post_meta( $post_id, 'sku', true ) === $query ) {
          $results[ $post_id ] = $weight * 1000;
        }
      }
      return $results;
    }

    This should lift exact matches in the sku custom field to the top of the results.

    Thread Starter kudiluv

    (@kudiluv)

    Excellent! It works. Is it possible to hide other products if found by SKU?

    Plugin Author Mikko Saari

    (@msaari)

    Yes:

    add_filter( 'relevanssi_results', 'rlv_exact_boost' );
    function rlv_exact_boost( $results ) {
      $query       = strtolower( get_search_query() );
      $sku_matches = array();
      foreach ( $results as $post_id => $weight ) {
        if ( get_post_meta( $post_id, 'sku', true ) === $query ) {
          $sku_matches[ $post_id ] = $weight;
        }
      }
      if ( ! empty( $sku_matches ) ) {
        return $sku_matches;
      }
      return $results;
    }

    This version will only return the exact SKU matches, if any are found, and the rest of the results if not.

    Thread Starter kudiluv

    (@kudiluv)

    Thanks

Viewing 6 replies - 1 through 6 (of 6 total)

The topic ‘custom fields’ is closed to new replies.