Add search to your Ghost blog

Maintaining Wordpress has been a huge pain for us as an organisation and for me personally since I am not a big fan of php, Apache Tomcat, mySQL and monolith architectures in general. We were running our own Digital Ocean droplet having to renew the Let’s Encrypt certificate ever so often. Or as Kevin puts it, ‘Why I’m not the biggest Wordpress fan’.

Moving to Ghost was a breath of fresh air. Using Javascript throughout made me feel immediately comfortable. Sure there were some teething problems but nothing which we weren’t able to overcome. With the no fuss Ghost(pro) option we were up and running in no time.

blog.geolytix.net

At this stage I read that Kevin isn’t a fan of Ghost no more. All valid points in that article. Myself, I would like to add that the use of jQuery in the default casper theme is shocking. But I was most surprised to find out that there is sort of no default search on the Ghost platform.

Though there are some open source solutions out there. I looked at ghost-finder, ghost-search, or ghostHunter. I wasn’t too much taken by any of these. Being fairly competent at writing Javascript I decided to roll my own search by using the Ghost Content API. — Why is this not integrated in Ghost by default? Then again jQuery; Really?

Anyhow. Here is our search input on it’s own.

We just added the input to the navigation bar in a local Ghost instance and upload this modified Casper theme to our hosted Ghost(pro).

It’s also possible to add the input dynamically with a bit of script magic, but I’ll leave this to you as you might not want the input in the nav-right, or you may not even use the Casper theme.

A custom integration key was needed to connect the Content API with our Ghost host. We are only interested in the Content API key.

Did I mention that Content API must be imported into your hosted Ghost.

Let’s put the styles (for the input and drop down) and the script import in the ghost header.

The script as shown in the codepen goes into the Footer…

And that’s that.

As for the script itself. We load the title, url, and html content of our Ghost blog as data and pass this to the search function. The keyup event of the input form will split the search term by spaces and count matches in the html data. We sort the resulting array by combined occurrence count and display the top 5 results as the link title with with the URL as href in the results list.

EZ.

This wasn’t actually my first attempt. Prior to looking into the Ghost Content API I built a solution based on a Google Custom Search Engine (CSE). I got the idea from this Medium article.

Here is a working codepen for the same blog using a Google CSE.

I hope some of you may find this helpful.

Happy blogging.

Dennis