Algolia: Integrating With WordPress

Algolia: Integrating With WordPress

Introduction

Welcome to the second part of my article series. In the previous article, I talked in detail about Algolia, its advantages and compared it with other searching techniques. To get a better base for this article, it is recommended to read the previous article first.

Read it here

In this article, we will see how we can integrate Algolia with WordPress.

Algolia search plugin for WordPress is no longer supported?

After discussing with a lot of developers, Algolia realized that the WordPress plugin, while being easy to implement and use, did not provide the room for customization necessary to build satisfying, advanced search and discovery experiences on WordPress websites.

That's why algolia decided to double down on the new PHP API client instead. So, in the below sections, I will guide you on how to integrate Algolia with your WordPress application, index your content, optimize your relevance and build state-of-the-art Front-end experiences relying on the API client.

Minimum Requirements

Before starting the custom integration, here are the basic minimum requirements:

  • PHP version 5.3 or greater (PHP 5.6 or greater is recommended).
  • MySQL version 5.0 or greater (Version equivalent to 5.6 or greater is recommended).
  • Some payment gateways require fsockopen support (for IPN access).
  • Requires WordPress 4.4+.

Setting Up Algolia

Before moving further, I am assuming that you have set up your WordPress site.

We need to create a few files before moving forward. An algolia-custom-integration folder under the wp-content/plugins/ directory and an algolia-custom-integration.php file inside this new directory with the following content:

code.png

Import Algolia PHP client

You have two options to import the Algolia PHP client:

  1. You can use the composer to install the Algolia PHP client. For that, you need to execute the following command at the root of your plugin:
    composer require algolia/algoliasearch-client-php
    
  2. Download the latest version of the Algolia API client via GitHub Release page.

Screenshot 2020-12-23 at 12.48.37 PM.png

Paste the downloaded folder inside the plugin directory and rename the above folder as api-client. You need to run the following command inside the api-client folder from the terminal to create a new api-client/vendor/ directory with some required dependencies:

php ./bin/install-dependencies-without-composer

Before moving forward, you need to have an Algolia account to integrate it with your WordPress site. It can be a free account for learning purposes as the free account provides all the basic functionality required.

Instantiate the Algolia SearchClient

In the main plugin file algolia-custom-integration/algolia-custom-integration.php, we’ll instantiate the Algolia client and make it globally available.

After initializing the instance, we have to option to either we use our WordPress admin panel to index our data for Algolia or we can use the Algolia dashboard to upload and update the data. Following the first approach is much more complex, but we can also use the second approach as it's much easier to follow and integrate and we can also use this approach with any other JavaScript framework that you feel like.

Here, we will follow the second approach.

Building The Search Functionality

Now, we will build the search functionality. We are going to use InstantSearch.js for this. It's a library build by Algolia that comes in various versions:

  • Vanilla Javascript
  • React.js
  • Vue.js
  • Angular.js

Here, I am going to use Vanilla JS to integrate it with our website, and the process for all the other JavaScript frameworks will almost be the same, so you can use any one of them as per your requirements.

We will go step by step for Building Search:

  1. Download the latest version of instantsearch.production.min.js by clicking the name as well as algoliasearchLite.min.js

  2. Save the files in your theme. For this documentation, we’re going to store them in a themes/your_theme/js/vendor/ folder

  3. Your theme’s functions.php register the JS files. We register them to be loaded in the footer of the theme. Note that we are specifying that InstantSearch must be loaded after the Algolia client via the third parameter of wp_enqueue_script. code2.png

  4. If you want some default CSS, you can download the one provided by Algolia with the filenamealgolia-min.css. Add this line at the end of the algolia_load_assets function:
    **wp_enqueue_style( 'algolia-theme', get_template_directory_uri() . '/algolia-min.css');**
    

At this point we are almost done with the setup. We need to build the UI to render the search results.

  1. To add the search bar, you need to add below HTML code where you want the search bar:
    <div id="searchbox"></div>
    <div id="category"></div> 
    <div id="content"></div>
    
    For the results, we’re going to use the #content tag to make a full-page results list.

Setting up InstantSearch for the search functionality

Create a new js/algolia-search.js file in your theme and add it in the algolia_load_assets function.

Go to your Algolia admin dashboard and under the API Key tab, copy the search-only API key. From now, all the Algolia integration-related code will be present in this new file.

code4.png

I will discuss each function one by one and address the need for these.

const search = instantsearch({
  indexName: "YOUR_INDEX_NAME",
  searchClient,
  searchFunction(helper) {
    if (helper.state.query) {
      helper.search();
    }
  },
});

This function creates an instance of the particular Algolia index you have provided with the indexName param.

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: '#searchbox',
    limit: 5,
    showMore: true,
  }),

This function will append the search bar provided by Algolia inside the #searchbar container. These widgets have multiple params that you can select as per your need.

instantsearch.widgets.refinementList({
    container: '#category',
    attribute: 'category',
  }),

refinementList: One of the most common widget you can find in a search UI. With this widget, the user can filter the data set based on facets.

instantsearch.widgets.hits({
    container: '#content',
    templates: {
      item: `
      <article>
        <a href="{{ url }}">
          <strong>
            {{#helpers.highlight}}
              { "attribute": "title", "highlightedTagName": "mark" }
            {{/helpers.highlight}}
          </strong>
        </a>
        {{#content}}
          <p>{{#helpers.snippet}}{ "attribute": "content", "highlightedTagName": "mark" }{{/helpers.snippet}}</p>
        {{/content}}
      </article>
    `
    }
  })
]);

search.start();

hits: It's a widget to display a list of results. You can also configure the number of hits to show, use the hitsPerPage widget or the configure widget.

Now, we will index some dummy data to our Algolia account.

Algolia Dashboard Configuration

  1. Create the new app and name it. After that, you can choose between various plans provided by Algolia as per your requirements. Here, we are using the free community plan. Screenshot 2020-12-24 at 1.29.25 PM.jpg
  2. Click the create button with the selected plan.

Screenshot_2019-12-13_at_12.30.06_PM.png

Start your search configuration

  1. Create the Index and name it. Be specific with name as further on, we will only use this key to perform the search.

  2. Click on the configuration tab to configure your Index.

  3. We need to upload some data on which we can perform the search. You have three options to upload the record:

    • Add manually.
    • Upload file ( CSV JSON TSV format only ).
    • Use the API.

Here, we will upload the record CSV file. After the record as a been updated, we need to do the Relevance Essentials setting. Screenshot_2019-12-13_at_12.49.36_PM (1).png

  1. Add a Searchable Attribute: which you want the user to search on the search bar to get the result i.e you can use the name of the product or brand name as a Searchable Attribute.

  2. Configure the Filtering and Facets: This method enables you to search through the values of a facet attribute, selecting only a subset of those values that meet given criteria. So you need to select the attribute which to act as facets i.e you can select product category and brands as parameters to filter out the result. Screenshot_2019-12-13_at_1.12.53_PM.png

  3. Lastly, we need to provide the list of all the Attributes to retrieve.

You don’t always need to retrieve a full response that includes every attribute in your index. Sometimes, you may only want to receive the most relevant attributes or exclude attributes used only for internal purposes.

You can find this setting under the Search behavior heading within the Setting bar.

Congratulations you have successfully integrated Algolia into your WordPress application.

I hope you you liked this article series. Do leave some likes and comments. If you have any questions, leave them in the comments and I will try my best to answer them.

Thanks so much.