Algolia Instant Search Bar for Woocommerce

Algolia is perhaps my preferred search tool because all the work is done on Algolia servers rather than the local database.  Because of the larger sites I work on, I offload the search grunt work to Algolia which leaves all the site speed resources for its users.

Algolia transforms the standard WordPress search bar and gives it super powers. Users will search more, stay longer and convert better. It’s what every site owner wants. Just by using a better search bar.

Algolia is essentially a very big, very fast database for returning search results similar to that used by search engines such as google. Algolia also has an Artificial Intelligence (AI) tool to learn.

Any application or platform can use it. Government websites, apps, ecommerce sites. There are plenty of ways it can be used.

Algolia uses instant search technology which triggers search results the moment users start typing into your wordpress search bar. The search is complete with thumbnails, titles, prices and custom text.

Visitors can find things quickly and easily. Algolia research shows increased search sessions of up to 60%, more page views per session, increased conversion rates and fewer “no result” queries.

Algolia WordPress Plugin

Using a wordpress plugin, Algolia collects information from your site and returns it as instant search results to your website users.  According to Algolia research, results are returned within 1- 20 milliseconds!!

And the beauty is … it can be used on any type of hosting. Even on cheap and nasty hosting, the results are instant. This is because the computing is done at Algolia and sent back via javascript that is already loaded into your search bar. Clever!

Algolia will sort and rank your results according to a set of predefined rules which you set. Herein lies its power. For instance you can define all your sticky posts or featured products to be listed toward the top of search results. Or you can list all ecommerce sale products toward the top of the list. There are plenty of ways in which you can rank, sort and prioritize results to present to your users. Think of it as a way to present or promote content in a customized way. Or better still, consider a customer walking into a store searching for an item. You show them your best selling items first, then you might show them something more expensive and then something else. Your Algolia search index can be customized in exactly the same way to take your customers on a journey through your site.

Consider how the google search engine works. We have all heard of the google search “algorithm”. There are many complexities built into the algorithm to tailor individualized search for a richer search experience. Algolia provides us the tools to build search experiences for our website users.

Setup

Is Algolia easy to set up? Well… Yes and No.

Out of the box Algolia for WordPress for novice users is easy enough to setup.  Open an Algolia account and install the plugin, copy and paste the API key and your are set.  A one click button pushes your data to Algolia in just a few minutes and your search bar and results page works straight away.  If that is all you need then you are golden.

Setting up the sorting and ranking can be done from the Algolia dashboard. This is where your data lives and is controlled from here, not from WordPress. The default settings work just fine but if you want to get your hands dirty with some custom sorting and ranking, set aside some time to become familiar with the Algolia indexing functions. It’s not difficult but if you are unfamiliar with search indexes, there’s a slight learning curve.

Algolia dashboard settings are applied immediately and can be seen on your site straight away. Some trial and error is needed but luckily Algolia has very good documentation every step of the way.

Customizing the search bar display (ie colours, font sizes, fields etc..) happens on your wordpress website and this is where some coding experience is needed. This is where Algolia for wordpress “out of the box” ease of use for the average user ends and some knowledge of coding languages start.

At this point I recommend a development site to test your code before deployment because it you make a mistake in your code you may break the site.

Algolia WordPress/Woocommerce Customisation

The Algolia wordpress plugin is now maintained by WebDev Studios rather than Algolia themselves. They have made some significant improvements and WebDev studios have compiled some excellent Algolia documentation to extend the instantsearch and autocomplete wordpress files. For most sites, the documentation provides plenty of examples. Other Algolia for WordPress plugins can be found in the wordpress plugin library, but the plugin by WebDev Studios is the one I prefer to use simply because their documentation is far superior and their support is good too.

The following code snippets apply to Algolia autocomplete and instantearch for woocommerce sites.

Algolia Instant search bar

Autocomplete.php styling

Here we will customise the search bar autocomplete seen in the above image by :

  1. Adjusting the size of the product thumbnail
  2. Style the heading
  3. Add in a product price or sale price.
  4. Add in custom text to show “sale” and/or special products
  5. Send extra woocommerce fields to Algolia eg featured, brand etc…

I’ll write another tutorial to style the instant search page and add in some facets.

Always use a child theme when making changes to templates.

We will be making edits to 3 files

  1. functions.php (saved in your child theme folder)
  2. style.css (saved in your child theme folder)
  3. Autocomplete.php (copy and save to /wp-content/themes/<child-theme-name>/Algolia)
  4. Instantsearch.php (copy and save to /wp-content/themes/<child-theme-name>/Algolia) – explained in another tutorial coming soon.

The 2 template override need to be saved into their own folder. Explained here
https://github.com/WebDevStudios/wp-search-with-algolia/wiki/Customize-Templates

Both templates are saved into custom Algolia folder inside your child theme

Open all files in your favourite editor (I like to use notepad++)

Step One – Gather our Data

The Algolia for wordpress plugin sends a default set of data to Algolia. It doesn’t send absolutely everything. That would be crazy. So we may need to send some extra data when WP does the push. Because we are using woocommerce products, there are few extra bits of data that I want sent across to Algolia to be used for searching and sorting. I want to send price, regular_price, sale_price, featured, catalog_visibility and sku. To do that, add the following code your functions.php file

function algolia_wc_post_shared_attributes( array $shared_attributes, WP_Post $post) {
    	
	$product = wc_get_product( $post );

	$shared_attributes['price'] = (int)$product-&gt;get_price();
	$shared_attributes['regular_price'] = (int)$product-&gt;get_regular_price();
	$shared_attributes['sale_price'] = (int)$product-&gt;get_sale_price();
	$shared_attributes['featured']=$product-&gt;get_featured();
	$shared_attributes['catalog_visibility']=$product-&gt;get_catalog_visibility();
	$shared_attributes['sku']=$product-&gt;get_sku();
	
    return $shared_attributes;
}
add_filter( 'algolia_post_product_shared_attributes', 'algolia_wc_post_shared_attributes', 10, 2 );

Next, I only want to push visible products to Algolia. I don’t want hidden products appearing. I don’t want posts and pages appearing in the search bar results either. I want to exclude those from the push.

To do that, add the following code to your functions.php file.

function wds_algolia_exclude_post( $should_index, WP_Post $post ) {
	
	// If a page has been marked not searchable
	// by some other means, don't index the post.
	if ( false === $should_index ) {
		 return false;
	  }
 
	if ($product = wc_get_product( $post )) {
		$excluded = $product-&gt;get_catalog_visibility();
		  // If not, don't index the post.
		  if ($excluded != 'visible') {
			 return false;
		  }
	}
	
	if (get_post_type($post)=='post' || get_post_type($post)=='page' ) {
		return false;
	}
	

  // If all else fails, index the post.
  return true;
}
add_filter( 'algolia_should_index_searchable_post', 'wds_algolia_exclude_post', 10, 2 );
add_filter( 'algolia_should_index_post', 'wds_algolia_exclude_post', 10, 2 );


Save your functions.php file.

Next push your data to Algolia. From your WP Dashboard, Select Algolia Search->Autocomplete and click the Re-index button.

Head over to your Algolia dashboard and check that all your new data eg price etc… has been captured correctly. Once we have the data squared away we can start working on templates.

Step Two – The Search Bar – autocomplete.php template

Open autocomplete.php and on about line 20 look for script block id= “tmpl-autocomplete-post-suggestion” and REPLACE the script block with the one below. We have removed the product description (we don’t need that in the search bar) and we have added the woocommerce price field and some custom text to indicate whether the products is on sale.


<script type="text/html" id="tmpl-autocomplete-post-suggestion">
	<a class="suggestion-link" href="{{ data.permalink }}" title="{{ data.post_title }}">
	
		<# if ( data.images.thumbnail ) { #>
			<img class="suggestion-post-thumbnail" src="{{ data.images.thumbnail.url }}" alt="{{ data.post_title }}">
		<# } #>
		
		<div class="suggestion-post-attributes">
		
			<span class="suggestion-post-title">{{{ data._highlightResult.post_title.value }}}</span>
			Price: $ {{ data.price }} 
			
			<# if (Number(data.sale_price)) {#>
				<span style="color:red;">  SALE/Catalogue</span>
				
			<# } #>
		</div>
	</a>
</script>

Save the file.

Step 3 – Style the Search Bar

Now we need to style it by adding a some css.

Open your style.css file from your child theme folder and add in the following styles.


/**********************************************
*** Algolia Autocomplete Instant Search CSS ***
**********************************************/

.aa-dropdown-menu .suggestion-post-thumbnail {width: 36px;} /* contol width/height of thumbnail */
.aa-dropdown-menu .aa-suggestion .suggestion-post-title {font-size:14px;} /* product title */
.ais-headline {padding:0px;font-size:16px;font-weight:800;}/* Search bar PRODUCTS heading */
ol li.ais-Hits-item::marker {content:"";}/* removes any content that may exist in the marker */
#algolia-powered-by {display:none;}/* removes the algolia logo */
.ais-line {border:0;border-top:1px #eee solid;}/* style drop down list */
.ais-Hits-item {margin:0 0 10px 0}/* adds margin to bottom of each product */
mark {background-color:#ffffe6;}/* mouseover background highlight */

Step 4 – Auto Sync – Keeping Your Data up to Date

Each time you make a change to a wordpress post or product, the data is automatically pushed to Algolia. For most users this is all you need.

But if you have an automated price script that updates thousands of product prices overnight, you may need to push all the data once it’s finished. This requires some expertise.

The Algolia for wordpress plugin ships with built- in WP-CLI (WordPress Command Line Interface) commands that will push data to Algolia. It’s unlikely that WP-CLI will be installed on shared hosts… but it’s worth asking your web host all the same.

Create a file in your child theme algolia_bulk_update.php and add the following code

&lt;?php
exec('wp algolia reindex --all');
echo "reindex complete";
?&gt;

Save the file.

Setup a cronjob on your server to run each day and trigger the above script. Or if you don’t have access to cron jobs you can set up an external con at cronjob.org and trigger the script remotely.

Damon
Damon

Damon is the Principal Full Stack Developer at WPFix and freelance consultant. If you need help implementing anything wordpress related, please reach out to make an appointment.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Recent Posts

  • Setup a Wordpress Child Theme slider
  • Wordpress Better SEO GTMerix and Ligthouse Scores slider
  • woocommerce disable rich text editing for shop managers slider
  • Woocommerce admin multi SKU search slider
  • Wordpress Enhanced Search slider