Adding Shopify’s Predictive Search to your Shopify Theme

Jon
2 min readMar 31, 2021

Adding Shopify’s predictive search to a theme looks extremely complex when first looking at it, and Shopify has made it look this way. Though, in this tutorial we’re going to add a simple search box to your theme — with 0 overheads and a simple AJAX script.

In this tutorial, we’re using basic Bootstrap styling.

Make sure Jquery is loaded!

  1. At the bottom of theme.liquid add the following code:
$('#searchInput').keyup(function(){
var q = $('#searchInput').val();
var b = '&resources[type]=product'

$.ajax('/search/suggest.json?q=' + q + b,{
type: 'GET',
dataType: 'json', // added data type
success: function(response) {
console.log(response);
var productSuggestions = response.resources.results.products;
if (productSuggestions.length > 0) {
$("#searchResults").empty()
$(productSuggestions).each(function() {
$("#searchResults").append(
'<li class="list-group-item list-group-item-action d-flex align-items-center"><div class="image-parent mr-3"><img class="img-fluid" src="' + this.featured_image.url + '"/></div><div><p class="mb-0">'+ this.title +'</p><small>' + this.body + '</small></div><p class="ms-auto">' + this.price + '</p></li>'
);
console.log(this.title);
console.log(this.price);
console.log(this.featured_image.url);
});
} else {
$("#searchResults").empty().append(
'<li class="list-group-item list-group-item-action d-flex align-items-center"><small>No Results Found</small></li>'
);
}
}
});
});

This code is far from “Perfect”, but it’ll get predictive search into your theme and allow you to expand on it.

2. Add a search form and a box for our results.

<form class="d-flex" action="/search">
<input id="searchInput" class="form-control me-2 border-0 search-box" type="text" name="q" placeholder="Search" autocomplete="off">
</form>
<div class="result_box">
<ul class="list-group" id="searchResults">
</ul>
</div>

Load up your theme, and start typing in your search box. You should now see Shopify’s predictive search results appear underneath your search box, or, if you’re not running Bootstrap — it’ll look a tad broken.

Save yourself $10pm and just add it in. It’ll save tons on overheads and cut your costs.

--

--

Jon
0 Followers

Just a Brit who loves developing and designing websites!