Self Searching

It’s not a shock to anyone that at a decade old, LezWatch.TV (LWTV) has a lot of content. And the problem with that large a site is it can get really hard to search and properly find things. The built in WP search is fine for blogs and small-to-medium sites, but it’s not something you can tune and it’s not really easily configurable, which means it’s not going to do it for me.

What Are You Looking For?

When you start looking into making search ‘better’, you have to be clear in your mind about what better means. So I listed out what we absolutely had to have for this to be a win:

  • Typo forgiveness: If someone types in “Alex Sanvers” they probably meant “Alex Danvers” and we should find the right Alex.
  • Similar Names: There are a lot of characters with similar names, but also we have shows like Charmed and Charmed (2018).
  • Alternate Names: Shows also have their regional names. For example, Las Chicas del Cable is known as Cable Girls in the US. Both should work.
  • Countries Matter: People want to search for “kdrama” and that should be possible!
  • Actor Names: Actors marry, change their names, transition, you name it. If you look for an actor’s dead name, you should be pointed to the correct person.
  • Fallback: If my search tool breaks, use regular WP.

That’s really the back-end stuff. When you get to front end, I needed:

  • A modern UX modal that was screen-reader and accessibility friendly.
  • Dark mode support. Nuff said.
  • One search box, four kinds of results. The search in the header now shows Shows, Characters, Actors and Posts in tabs, with a count on each, and it updates as you type.

And then there’s making life easier for the admins:

  • A status page letting me know the health of the search server and my search indexes.
  • Control to let only editors or everyone use the new system, which allows for a testing period.
  • Customizable typo tolerance per index.

So not a lot at all, right?

SearchWP

Now first and foremost, we’ve been using SearchWP for about 2 years and it’s amazing. It’s fast, it’s easy to format and design, and you can get really picky about what is and isn’t searched. Quite frankly, if you have a site with under 20k posts (posts, pages, any custom post types), then you absolutely should look it up.

LezWatch.TV has around 15k posts (posts, pages, three custom post types) and they are very complex with a lot of metadata. And this is exactly where SearchWP hits its limit.

They’re totally honest about this! As I was adding in more and more data to be searchable, and the editors adding in more content, it got slower and slower. Honestly that’s just not a good experience. SearchWP officially suggested Algolia or ElasticSearch (be it Swiftype or ElasticPress) but I decided to do something else.

Meilisearch

Meilisearch is a flexible and powerful user-focused search engine that can be added to any website or application. I actually use it at work to self host our own engine. It’s incredibly fast, reliable, and pretty darn easy to install via Docker. The hard part is what we’ll get into.

Pick Your Battles

First I set some constraints on the work. There’s no point in trying to be everything, so you want to draw your lines in the sand before you start developing.

  • No new runtime Composer dependencies. The deploy strips vendor/, so there’s no meilisearch-php. I did look into changing that, but it would require a lot more work and not a lot of gain. A small Client class talks to the REST API through wp_remote_request().
  • The search server can never slow or break a save. Hooks only queue work in Action Scheduler; nothing calls Meilisearch during a save.
  • No key in the repo, a log or an error. Keys stay in wp-config.php. Errors report the HTTP status and Meilisearch’s error code, nothing more.
  • Nothing private reachable through the public key. Only published posts are indexed, and actors with privacy set are left out as documents and as names on other documents.
  • Logic is testable without WordPress. Every decision (document shapes, sync routing, job state, validation) lives in pure build/ classes covered by PHPUnit. The suite ended at 1,704 tests.

Four indexes, one registry

Each index is a class extending an abstract Index: characters, shows, actors, and one content index for posts and pages. Each knows its post types, its settings file and how to build documents, and answers one question: this post changed, which of my documents does that touch? A registry is the only list of types, so adding an index is one class plus a JSON settings file.

A change to…characters indexshows indexactors index
a characterthat characterits showsits actors
a showits charactersthat showits characters’ actors
an actortheir characterstheir showsthat actor

Each cell is one lookup on the character links table. Index settings live in config/{type}.json in the repo, applied with wp lwtv meili settings, and wp lwtv meili status reports any drift between the repo and the server.

Note: I am planning to get rid of the config json files, but since the decisions were pretty set in stone to start, it’s okay. For now.

Ranking Carefully

Meilisearch’s default ranking rules run first, then custom tie-breakers per index:

  • Shows tie on name because the title is split from its qualifier (“Charmed” + “2018”), so the plain title doesn’t win on exactness. Ties then go to Worth It, then score. “skins” finds the UK original, “charmed” the 2018 reboot. Score alone gets Skins wrong, recency gets Skins wrong, and character count gets Night Court wrong.
  • Characters rank the bigger role first: regular, then recurring, then guest.
  • Actors rank queer actors first, then those with more characters.
  • Content puts evergreen pages ahead of articles, then newer articles ahead of older ones.
  • Countries are the last searchable field on shows, with typos off, so a title match always beats “made in”. That’s what lets a kdrama ↔ south korea synonym list Korean shows.

Every search sends matchingStrategy: "frequency". Actors’ other names are searchable but excluded from displayedAttributes: they match, and they’re never returned.

Keeping the index in sync

Saves, renames, status changes and deletes queue one Action Scheduler task per post per index, five seconds out. The task works out the affected documents and sends them in batches of 100. Show score and actor recalculations fire their own actions, so ranking fields stay current.

Two rules made this safe to deploy:

  • Sync never creates an index. Meilisearch creates an index on the first document add, with default settings. Without this rule, the first editor save after a deploy would build a production index nobody approved. Only settings or reindex --fresh create one.
  • Drift repairs itself with a prune. reindex re-sends every published post, then deletes every document whose id isn’t in that set, with a filter that refuses an empty list.

The front end

  • Header modal. A native <dialog> with four ARIA tabs and one POST /multi-search per keystroke pause (150 ms). The browser uses the search-only key. A newer search aborts the older request and, until you pick a tab, the tab whose top hit scores highest is shown. A preconnect with crossorigin warms the CORS connection before the first search.
  • Results page. search.php asks Meilisearch for IDs only, server-side, then loads the posts with one get_posts() ordered by post__in and hands them to the main query through posts_pre_query. Core’s LIKE search and SearchWP never run.
  • FacetWP. Three Meilisearch engines appear in FacetWP’s search facet dropdown, using matchingStrategy: "all" so the box narrows the list, and intersecting with the archive’s other facets.
  • Fallbacks everywhere. Any network error, non-2xx response or timeout (2 seconds by default) drops back to SearchWP if it’s installed, or to WordPress search. An inline ES5 guard keeps the search button working if the module script never loads.

The config the browser reads is printed as <script type="application/json"> with JSON_HEX_TAG | JSON_HEX_AMP, so no string can close the script element. Search turns itself off if the search key equals the indexing key, so a wp-config slip can’t publish the indexing key on every page.

The admin side

A new Search menu holds Settings, Rules and Compare, built as one React bundle on @wordpress/components with WordPress doing the routing.

  • Status shows server health and each index’s document count, settings drift, synonyms and running job.
  • General has the off / editors / everyone switch, the fallback timeout, and the server URL and index prefix. The URL defaults to search. plus the site’s domain and the prefix to wp_get_environment_type(), so a new environment works without wp-config lines. Only overrides are stored, so a copied database computes its own defaults instead of keeping another site’s.
  • Typo tolerance is per index. Defaults live in code, and only differences are stored.
  • Rules holds synonyms in the database, because they’re editorial, and merges them into each index with a partial settings PATCH.
  • Compare puts Meilisearch and SearchWP results side by side. Every ranking decision above was checked here.

Reindex and Set up run as jobs: a pure state machine, one Action Scheduler action per step, 500 posts a batch. Batches page by the last post ID, not an offset, because steps can be minutes apart. Each job records a fingerprint of the server and index it started on, and fails cleanly if someone changes the connection mid-run.

Some Surprises on the Way

It wouldn’t be a deployment if you didn’t have them, would it?

FacetWP runs its own SearchWP query

Short-circuiting SearchWP’s native search wasn’t enough. FacetWP’s SearchWP integration runs its own SWP_Query for the main search, so the results page also has to return false from facetwp_is_main_query for that query.

s is still slashed at pre_get_posts

The query var still carries WordPress’s slashes, and on /search/term/ URLs it’s still URL-encoded. Read it the way core does: wp_unslash(), then urldecode() for pretty URLs.

Jobs need a nudge, and can queue behind a backlog

Action Scheduler’s async runner only fires on full admin page loads, and one environment had WP-Cron off, so the job code dispatches the queue runner itself. On staging, which doesn’t run the queue all the time, a Reindex sat at “0 sent” behind a backlog of older actions until it was cleared.

The sidebar’s suggestion list closed on focusout when the next focus target was outside it. Chromium focuses a link on mousedown; Safari and Firefox on macOS don’t, so relatedTarget was null, the list closed on mousedown, and the click landed on nothing. Cancelling mousedown inside the list keeps focus in the input and lets the click through in every browser.

A search term can break a format string

String.replace() with a string replacement reads $& as “the match”, so a search for $&showed “No results for %s”. A replacer function fixes it.

A missing plugin exposed an old duplicate

With SearchWP’s modal plugin off, the header printed a second copy of the old search box outside the navbar. It had been there since early 2025, and it only showed up as a 32px gap once the plugin was gone.

Done and Dusted

It took a week of very careful planning first, but from that to finish was only five days.

Do I recommend the for everyone? God, no! But if you have a large site and the idea of ElasticSearch’s cost is making you balk (and yeah, I’ve tried that and Algolia) but you want control and features?

Yeah, this is pretty damn nifty.

Leave a Reply

Your email address will not be published. Required fields are marked *