Using Algolia Search Results in WordPress

Using Algolia for your search results is a game-changer – it’s fast and accurate. While there are different plugins and JS solutions, I ran into an instance where I needed to have use it thru a shortcode (due to a third party theme). My solution was to drop it into my already existing custom plugin.

In this example, I’m going to be building off of my plugin scaffold and using a shortcode to display the results on my search page. The shortcode creation will live in the initActions method, keeping it nice and tidy. There will also be a separate file for the actual search result template.

Below is the shortcode skeleton – it checks for a search query and if so sets up the Algolia client and would set our searchResults, which will be used in the search results template.

add_shortcode('algolia_search', function () {
//Check to see if there is a query
$query = get_search_query();
if (!empty($query)) {
//Setup Algolia
//Set search results
} else {
$searchResults = false;
}
ob_start();
//include search results template
return ob_get_clean();
});

view raw
Loader.php
hosted with ❤ by GitHub

At this point, we can setup the Algolia client, pass the search query to it, and then pass that to our search results template.

add_shortcode('algolia_search', function () {
//Check to see if there is a query
$query = get_search_query();
if (!empty($query)) {
//Setup Algolia
$client = \Algolia\AlgoliaSearch\SearchClient::create(
'app_id;,
'api',
);
$algolia = $client->initIndex('index');
$algolia->setSettings([
'attributeForDistinct' => 'id',
'distinct' => true,
'hitsPerPage' => 1000,
]);
//Set search results
$searchResults = $algolia->search($query, [
'distinct' => true,
])['hits'];
} else {
$searchResults = false;
}
ob_start();
//include search results template
return ob_get_clean();
});

view raw
Loader.php
hosted with ❤ by GitHub

In this example, there is no pagination (as shown by the hits per page being so high), but if you want to have paging, that’s relatively easy to do as well. All we do is set the page variable in the Algolia client to whatever page we want. You could grab this from the URL (in the below example it’s just being set).

$algolia->setSettings([
'attributeForDistinct' => 'id',
'distinct' => true,
'hitsPerPage' => 20,
'page' => 2
]);

view raw
Loader.php
hosted with ❤ by GitHub

In the search results template, you can loop thru $searchResults and do whatever you need to do.