The other day I posted about trying to setup search on a static WordPress site hosted in an S3 bucket. I had tried the programmable Google thing, but that wasn't great. But I managed to get something working with Lunr.js.
This process is based on hosting WordPress 'offline' / locally, and generating a static site using something like Simply Static.
Step 1. Create an index
First thing you need is an index, something a JavaScript search app can go through. I found a WordPress Plugin designed to export the content of a blog to a JSON file, Exporting Blog Posts to JSON which was a great starting point, but then I updated it for me needs – specifically changing the format of the output to something that can be read by Lunr. I just zipped the PHP file and uploaded it to WordPress as a new plugin.
This plugin generates a JSON file of all the (written) content in the form of:
{
"id": “<internal WP post ID>”,
"title": “Title”,
"content": “ALL THE WORDS...”,
"url": "https://<internal non-public server>/2024/03/Title/“
},
When exporting the JSON file it has a URL which is based on my internal network and the hosted WordPress server I used for writing and updates – a quick find and replace in a text editor fixes that:
{
"id": “<internal WP post ID>”,
"title": “Title”,
"content": “ALL THE WORDS...”,
"url": "https://<public-host>/2024/03/Title/“
},
Now you have an index that can be easily searched by something, you need something. The something I found that worked for me is Lunr.
Step 2. Search Scripts
For my site I added a /search/
URL with a “WordPress page” that was pretty much blank. I had tried adding the HTML to the page as an “HTML” block, but Gutenberg and WordPress just kept destroying the code by adding random tags through it all. It did not understand it was supposed to be some scripts.
I also included lunr.js
as a file hosted in my S3 bucket – keeping everything needed locally to the host and not needing to rely on anything external.
Outside of the WordPress I edit the index.html
that is generated by the static export process to include the following code:
This has worked across all browsers I have tested it with and has worked pretty fast.