WooCommerce variation data in SearchWP results

SearchWP is, in my opinion, the best solution when it comes to search in your WordPress website. Besides providing a great user experience by actually returning good results, it’s well written and allows some nice extensions.

The situation which I’m going to provide a solution for is this: you have a WooCommerce website with variable products. Those products have some custom characteristics which you want to allow your users to search by.

Let’s go with an even more specific example. Let’s say the products are books, and each book has an ISBN. They are variable maybe in edition.

And you want to allow your customers to search by ISBN.

Indexing the data with SearchWP

If you’re not aware, SearchWP’s system is based on an index. The index goes through all the items/posts in the background and creates a structure which makes searching more efficient. But at the same time it allows you to set priorities for each info.

The first step to index the data properly is to make SearchWP aware of it. In order to do that we’ll need a bit of code added to either functions.php in your current theme or small custom plugin. I always recommend a custom plugin because in case you make a typo the plugin will be deactivated and you won’t kill the whole website.

In order to index the data, I used the hook “searchwp_extra_metadata“. This hook allows you to add extra data to be indexed for each post.

Now for the actual code:

As you can see, this is pretty straight-forward and give you great power on what data to associate to each post. You could also use this for example to associate relevant posts to one another or even data from taxonomies.

Resetting the index

Just adding the code above won’t do anything. You’ll need to go to the WordPress admin, navigate to Settings > Search WP. Select the post type you wish to change ( in our case Products ) and at the bottom click on “Add Custom Field”.

If the code is working properly, you will see the newly added key in that list ( in our case “m_product_isbns” ). Select that field, set its priority and save the settings.

Next, go to the “Advanced” tab and click on Reset Index. When the index finishes re-indexing the data, you’ll have the data properly attached to the products.