Skip to main content
For InstantSearch-powered pages like catalog search and categories, the extension handles the following for the InstantSearch implementation based on your configurations:
  • Implementing widgets for your search experience like search input field, facets, sorting, and results
  • Templates for your search UI like filters, results, and the toolbar
All the necessary files are in the vendor/algolia/algoliasearch-magento-2/view/frontend folder, which contains the templates, JavaScript, and style sheets in use.

Widgets

The InstantSearch UI consists of widgets, which have a predefined behavior and rendering. For example, the search input field is a widget, and the results is another widget. The extension defines a set of widgets for your InstantSearch UI based on your configuration settings in Stores > Configuration > Algolia Search > InstantSearch Results Page Here are some widgets that the extension leverages for its UI: In the image below of a basic InstantSearch configuration, each highlighted section is a widget: InstantSearch widgets If you need to add or change these preconfigured widgets, use the beforeWidgetInitialization event provided by the extension.
JavaScript
algolia.registerHook(
  "beforeWidgetInitialization",
  function (allWidgetConfiguration, algoliaBundle) {
    // add your code here
    return allWidgetConfiguration;
  },
);
The allWidgetConfiguration parameter has access to the set variable allWidgetConfiguration. This variable has all the InstantSearch widget configurations already created for you based on your extension settings. Using this event, you can return a modified allWidgetConfiguration for InstantSearch to render. The following sections reviews key implementation concepts to help better understand what events to target when customizing InstantSearch.

Layered navigation or facets

Magento defines the filters on the left column as layered navigation. Algolia calls them facets. InstantSearch builds these facet filters with refinement widgets like: The extension uses the configuration for facets set in Stores > Configuration > Algolia Search > InstantSearch Results Page > Facets, to define which refinement widget to use. You can use the algoliaConfig global in your developer tools console to review the configurations for the implementation using algoliaConfig.facets in your store front. InstantSearch facet output

Product results or hits

InstantSearch hits The hits and infiniteHits widgets display the product results from a search. The extension can configure either options. You can enable infiniteHits in Stores > Configuration > Algolia Search > InstantSearch Results Page > Enable Infinite Scrolling? Both widgets use the same template to render the item template: view/frontend/templates/instant/hit.phtml. To change the rendering of the product result, copy the template in your theme, and edit the copy instead of directly in the extension. If you need to add complex display conditions to your product hits, use the beforeWidgetInitialization event hook to transform the hit before passing in the variable to the template. These widgets have the option to transformItems, which accepts a callback function. As the extension already utilizes this parameter, make sure that you run the already created function before yours. For example:
JavaScript
define([
      'jquery', 
      'algoliaCommon',
      'algoliaInstantSearchLib',
    ], 
    function (
      $,
      algolia,
      instantsearch // Directly inject the instantsearch library as needed
    ) {
    algolia.registerHook('beforeWidgetInitialization', function(allWidgetConfiguration) {
        $.each(allWidgetConfiguration, function (widgetType) {
            if (widgetType == 'hits') {
                var callbackTransform = allWidgetConfiguration[widgetType].transformItems;
                allWidgetConfiguration[widgetType].transformItems = function(items, { results }) {
                    items = callbackTransform(items, { results });
                    return items.map(function (item) {
                        // add your modification to item result
                        item.exampleNewVariable = 'This is an example that will be applied to all items.';
                        console.log(item)
                        return item;
                    })
                }
            }
        });

        return allWidgetConfiguration;
    });
});
The preceding example adds a new attribute variable on the fly for the hits. You can access the new attribute variable by adding the variable to the hits template: {{{exampleNewVariable}}} InstantSearch hits modified Use the beforeWidgetInitialization frontend hook to add more complex logic for your product listing.

Custom events

The extension offers several events within the InstantSearch implementation:
  • beforeInstantsearchInit(instantsearchOptions) Changes default instantsearch options.
  • beforeWidgetInitialization(allWidgetConfiguration) Adds, removes, or updates any widget.
  • beforeInstantsearchStart(search) Changes the instantsearch instance before calling the start() method.
  • afterInstantsearchStart(search) Changes the instantsearch instance after calling the start() method.
  • beforeFacetInitialization(builders) Modifies the rendering logic for any facet.
All custom methods must return the manipulated first parameter.

Change search options

If you need to change the InstantSearch search options, whether changing the index name or tapping directly to InstantSearch events, you can use the event: beforeInstantsearchInit Use this event to change the instantsearchOptions option which accepts a callback function. As the extension already utilizes this parameter, make sure that you run the already created function before yours. For example:
JavaScript
// Modify default `instantsearchOptions`
algolia.registerHook(
  "beforeInstantsearchInit",
  function (instantsearchOptions, algoliaBundle) {
    instantsearchOptions.numberLocale = "fr";
    instantsearchOptions.onStateChange = function ({ uiState, setUiState }) {
      // Add your logic here
      setUiState(uiState);
    };

    return instantsearchOptions;
  },
);

Change search parameters

The method to change the searchParameters for your search request depends on your extension version. In version 1, change this parameter in search options. In versions 2 and later, the configure widget sets the search parameters. This widget accepts an object of searchParameters. For example:
instantsearch.widgets.configure({
  hitsPerPage: 8,
  distinct: true,
  clickAnalytics: true,
  enablePersonalization: true,
});
As the extension implements the configure widget for you, use beforeWidgetInitialization to make any changes to it. The example below shows how to change and add preconfigured values using the event hook:
// Modify default `searchParameters`
// see: https://www.algolia.com/doc/api-reference/api-parameters/
algolia.registerHook(
  "beforeWidgetInitialization",
  function (allWidgetConfiguration) {
    allWidgetConfiguration["configure"] =
      allWidgetConfiguration["configure"] || {};

    // change hitsPerPage
    allWidgetConfiguration["configure"].hitsPerPage = 20;

    // change enabledPersonalization
    allWidgetConfiguration["configure"].enabledPersonalization = true;

    // Adding a custom Query Rule context
    var newQueryRuleContext = "new-custom-query-rule-context";
    allWidgetConfiguration["configure"].ruleContexts.push(newQueryRuleContext);

    return allWidgetConfiguration;
  },
);

Add new widgets

The following code shows how to add the toggle-refinement widget to the InstantSearch page:
algolia.registerHook(
  "beforeWidgetInitialization",
  function (allWidgetConfiguration) {
    const wrapper = document.getElementById("instant-search-facets-container");

    const widgetConfig = {
      container: wrapper.appendChild(createISWidgetContainer("in_stock")),
      attribute: "in_stock",
      on: 1,
      templates: {
        label: "In Stock",
      },
    };

    if (typeof allWidgetConfiguration["toggleRefinement"] === "undefined") {
      allWidgetConfiguration["toggleRefinement"] = [widgetConfig];
    } else {
      allWidgetConfiguration["toggleRefinement"].push(widgetConfig);
    }

    return allWidgetConfiguration;
  },
);

Templates

Follow best practices when you update templates in the extension. Keep changes in your theme directory and avoid directly editing the extension.

InstantSearch page wrapper

The wrapper template holds the layout of the InstantSearch results page, along with all other templates rendered in to it. To alter the layout of this page, go to the templates directory, and locate the wrapper.phtml file. This file is a standard Magento template file.

InstantSearch results page

To change the structure of the widgets on the results page, go to the instant folder of the templates directory. Here are the files used to render the configured widgets:

Mustache templates

In the Magento extension, the Autocomplete and Recommend templates use the JavaScript-based approach. The InstantSearch templates still rely on Hogan.js which is still supported in InstantSearch.js v4. A Mustache-based template parser, such as Hogan.js, must be loaded explicitly in these files:
  1. wrapper.phtml
  2. stats.phtml
If you relied on the bundled Hogan.js library in your customizations, you need to update your code. In previous versions, Hogan.js was included in algoliaBundle. Since the algoliaBundle is discontinued in version 3.15.0, Hogan.js is now packaged as a separate library that can be loaded through RequireJS as needed. However, Hogan.js is unmaintained and security concerns persist. That’s why Mustache.js is the default templating engine.

Template engines

You don’t have to use Mustache.js if it doesn’t suit your purpose. You can use RequireJS mixins to specify an alternate template engine. For example, to use Hogan.js instead of Mustache.js, you can write a mixin on the getSelectedEngineType function:
  • requirejs-config.js
    js
    const config = {
      config: {
          mixins: {
              "Algolia_AlgoliaSearch/js/internals/template-engine": {
                   "Algolia_CustomAlgolia/js/internals/template-engine-mixin": true,
              },
          },
      }
    };
    
  • template-engine-mixin.js
    JavaScript
    define(function () {
      "use strict";
    
      return function (target) {
          const mixin = {
              getSelectedEngineType: function () {
                  return target.ENGINE_TYPE_HOGAN;
              },
          };
    
          return { ...target, ...mixin };
      };
    });
    
For more examples of how to use mixins or hooks to customize the Algolia frontend in Magento, see the CustomAlgolia sample module.
I