Category: AI Search

  • llms.txt for ecommerce: what belongs there, what doesn’t

    The quietest file on the internet right now is /llms.txt. Most stores don’t ship one. Most owners I talk to haven’t even heard of it. And most of the writeups you’ll find online are about documentation sites — which is useful if you ship an SDK, and not very useful if you sell running shoes.

    I think it’s also the file most likely to decide whether an AI agent cites your store in a shopping answer next year. So this piece is a practical, opinionated reference for the ecommerce case — a bit of a deep dive on one of the seven items from an earlier piece I wrote on being readable by AI agents. A docs site and a product catalogue send very different signals, and a well-written llms.txt is the shortest way to tell an agent what you’re actually known for.

    1. What llms.txt is — and what it’s not

    Jeremy Howard proposed llms.txt back in September 2024. It’s a plain markdown file at your site’s root — https://yourstore.com/llms.txt — and that’s really all it is. Think of it as a curated map, not an access control list. It says what you want AI agents to read; it doesn’t say whether they can.

    Three files sit near each other in your root and people confuse them all the time. They do different jobs:

    • robots.txt — access control. Allow or deny crawlers. Binary.
    • sitemap.xml — full URL index for search engines. Exhaustive.
    • llms.txt — curated best-of for AI agents. Opinionated.

    If sitemap.xml is your warehouse inventory list, llms.txt is your window display.

    It’s still a convention, not an RFC. No standards body governs it (yet). But adoption is quietly compounding, and the upside of shipping one is wildly disproportionate to the fifteen minutes it takes to write.

    2. The three files

    Three related files have emerged around the convention. Honestly, you probably don’t need all three — I certainly don’t ship all three.

    • /llms.txt — short index with links to your key pages. The main file. If you only ship one, this is it. Aim for under 50 KB.
    • /llms-full.txt — the concatenated full text of those key pages inline. Saves the agent N fetches. Worth shipping if your catalogue is small and your policy pages are stable. Practical ceiling: around 500 KB.
    • /llms-ctx.txt — a context-trimmed variant for faster, cheaper agent runs. Rare in practice. Skip it for v1.

    For almost every store: just ship /llms.txt. If your catalogue is small and your policy pages are stable, add /llms-full.txt too — it genuinely saves the agent round trips, and it’s easy to generate. Ignore /llms-ctx.txt until you have a specific reason not to.

    3. The format

    Pure markdown, specific shape. One H1 at the top (your store or brand name), an optional one-line blockquote as a summary, then H2 section headings, each with a bullet list of [Link title](URL): one-line description. Here’s what it looks like in full:

    Keep descriptions tight. One line, no marketing adjectives. Agents cite facts, not vibes — a product is “waterproof, 280g, 4mm drop” rather than “our premium flagship trail companion”. The second one reads as filler and gets skipped.

    4. llms.txt for ecommerce: what belongs, what doesn’t

    This is where every generic llms.txt writeup falls apart: they’re written for documentation sites, where the structure is a tree of concepts with a few canonical entry points. A product catalogue is a completely different shape. Here’s what actually belongs in a store’s llms.txt:

    • Homepage, with a one-line description of what you sell.
    • Top-level category pages (not every facet combination).
    • Policies: shipping, returns, size guide, warranty, materials, sustainability. These are the pages agents cite most often in answers.
    • About or brand story page — the “who are you” page agents cite for provenance.
    • FAQ, if it’s real. Not SEO-filler FAQ.
    • Top 10 to 20 products that represent your catalogue. Not more.

    And here’s what doesn’t belong:

    • The full product catalogue. Giving an agent all 10,000 products is the same as giving it none.
    • Cart, checkout, account, login, wishlist, order tracking. No public value.
    • Search results, facet filters, sort variants — anything with ?color=blue or ?sort=price.
    • Thank-you pages, 404s, duplicate canonical variants.
    • Blog or press, unless they’re your main content asset — then only the evergreen top five.

    The thing to internalise is “top N, not all N”. llms.txt is a quality signal, not an exhaustive index. That’s what sitemap.xml is for. Curate ruthlessly — if an agent summarising your store couldn’t name what you’re known for after reading the file, you’ve included too much.

    Which ten to twenty products? Pick your hero SKUs: the ones your best customers actually mention, the ones your merchandiser puts on the homepage, the ones you’d demo on a pitch call. If you sell 500 running shoes, five of them represent the brand. List those five. The other 495 live in sitemap.xml and they’re fine there.

    5. Common mistakes

    Six patterns I keep running into that silently hurt citations.

    • Copying sitemap.xml wholesale. Every other mistake on this list follows from this one. llms.txt is curated. sitemap.xml is comprehensive. Keep them separate.
    • Tracking parameters in URLs. ?utm_source=llms defeats the purpose. Use clean canonicals.
    • Non-canonical variants. Listing /products/x1?color=black instead of /products/x1. If the URL changes based on options, link to the canonical form.
    • Blocking the same agents in robots.txt that you’re inviting in llms.txt. Check your robots.txt doesn’t Disallow: / for GPTBot, ClaudeBot, PerplexityBot, Google-Extended.
    • Stale links. Your relaunch moved /shop/items/* to /products/* and your llms.txt still points at the old paths. 404s teach agents to stop reading the file.
    • Marketing copy instead of facts. “Our premium flagship product” is unquotable. “Trail-running shoe, 280g, 4mm drop, Portuguese-made” is a shopping answer waiting to happen.

    6. Who actually reads llms.txt in late 2026

    Honest answer to the question everyone asks. Nothing in this section is official — none of the vendors below publish formal support docs for llms.txt — but all of it is observable in agent behaviour and server logs if you watch for it.

    • Perplexity — reads and uses it. Routinely cites llms.txt-listed pages in shopping and research answers.
    • ChatGPT with web browsing — fetches /llms.txt opportunistically when GPT visits a domain. Uses it to decide which pages to read next.
    • Claude (search and fetch tools) — reads it when an agent is pointed at your site, and uses the index as its retrieval plan.
    • Google Gemini / AI Overviews — inconsistent in practice. No public statement. Citation behaviour has been observed but unreliably.
    • Open-source agents (LangChain-based pipelines, autonomous frameworks, custom retrievers) — a common pattern is to probe /llms.txt first before falling back to crawling.
    • Bing, DuckDuckGo, Yandex — no visible support.

    My honest reading: llms.txt is already load-bearing in the retreival ecosystem that drives Perplexity, Claude and ChatGPT. Adoption is uneven, sure, but the asymmetry works in your favour — the cost of shipping one is fifteen minutes, and the cost of not shipping one compounds every quarter as more agents check for it first.

    7. Generating and updating it

    The right generation strategy depends on your stack. The right update cadence is “whenever your top-products list changes” — which for most of the stores I work with means once a month, give or take.

    Static sites (Framer, Astro, Hugo, Next.js): commit llms.txt to the repo and ship it with each release. Treat it as a first-class source file.

    WordPress: a few plugins exist as of late 2026 but honestly, they’re mostly immature. For most sites, a small snippet in a mu-plugin keeps it under your control and avoids an extra dependency:

    Shopify: no native support here. Either use a Liquid page with a text/plain output, a dedicated app, or host the file on a subdomain you control. Webflow and Framer: use their static file options with the right MIME type and you’re done.

    One more thing on updates: if your URL structure changes, update llms.txt first and only then redirect the old URLs. Otherwise agents hit 404s before your redirects land, and they learn to stop trusting the file. I’ve seen this kill citations after a migration more than once.

    8. Verify yours works

    Four checks, in this order. Run them after your first publish and then whenever you edit the file:

    • The response must be 200 OK with Content-Type: text/plain. Plain text renders everywhere; text/markdown fails on some agents.
    • Every URL in the file must return 200. No 404s, no redirects to different URLs.
    • The markdown must parse — a broken list breaks the whole index.
    • Final check: paste the content of your llms.txt into an AI agent and ask “based on this file, what does this store sell?”. The answer should match your positioning. If it doesn’t, your file is the problem, not the agent.

    If you’re reading this at 11pm and want to just get started: write a twenty-line llms.txt with your homepage, your top five policy pages, your top ten products, and your about page. Ship it tonight. Audit the URLs tomorrow. Put a monthly reminder somewhere you’ll actually see it.

    The file costs essentially nothing to ship, and every quarter more agents respect it. The cost of not shipping it is becoming invisible to exactly the kind traffic that’s growing fastest — the shopper who just asked ChatGPT “what’s a good trail shoe under €150 made in Europe” and expected a real answer.

  • Ecommerce sites: how to be readable and cited by AI agents

    Traditional SEO was about ranking for a query. AI agents don’t rank — they cite. Your product page either becomes a fact a model quotes when someone asks it for “the best waterproof running shoes under €80”, or it gets skipped as div-soup. Being invisible to agents in 2026 is what being invisible to Google was in 2010.

    AI crawlers don’t work like search crawlers. They read the HTML, extract structured claims, compare the facts across sites, and only then synthesise an answer that may or may not mention you. The seven items below are what decide which side of that outcome you land on. None are expensive. Most take a weekend. All of them compound.

    1. Ship real Schema.org structured data

    This is the single highest-leverage item on the list, so start here. Agents treat JSON-LD as a pre-parsed fact sheet — no scraping heuristics, no guessing where the price lives, no fighting your markup. The signal-to-noise is unbeatable and every major agent respects it.

    The minimum to ship: Product (name, image, description, sku, brand), Offer (price, priceCurrency, availability, priceValidUntil), and BreadcrumbList. If you can add AggregateRating, Review, or a per-product FAQPage, do.

    What trips people up, in the order it trips them: priceValidUntil missing (Google complains, agents deprioritise), availability written as the string “in stock” instead of the full https://schema.org/InStock URL, and image as a relative path. If you’re on WooCommerce, the stock schema output or the Yoast SEO WooCommerce addon cover this — but audit what is actually on the page, don’t trust a plugin’s claim that it’s there.

    2. Keep the HTML semantic and the DOM clean

    Agents parse the DOM top to bottom. They don’t run your JS runtime, they don’t wait for your hydration, and they don’t click “load more”. The HTML that arrives in the first byte is the HTML they read.

    One <h1> per page (the product name), a <main> landmark, specs in a <dl> or a <table> instead of <div><span><span> nested four deep, <nav> for the breadcrumb, <footer> for the footer. If the site was built in a page-builder, open view-source on a product page and ask yourself: could a reader without CSS make sense of this?

    The litmus test: strip every stylesheet from the page. If a human can still understand it, an agent can too. If it collapses into an unreadable list of acronyms, the agent gave up two seconds in.

    3. Write product copy as facts, not as marketing

    Agents cite claims. Adjectives aren’t claims. “Soft, breathable, and made with care” is unquotable — no model will drop it into an answer, because it means nothing specific. “100% organic cotton, 180 gsm, GOTS-certified, dyed in Portugal, machine wash cold” is a shopping answer waiting to happen. The first sentence sounds nicer. The second one gets cited.

    You don’t lose brand voice — you move it. Keep the warmth in the headline and the opening paragraph. The spec body, the one further down the page that agents index deepest, should lead with material, dimensions, origin, certification, care. The same copy also makes your on-site semantic search work, because semantic search and external agents are both looking for the same thing: meaning you can actually state.

    4. Set an honest AI crawler policy — robots.txt and llms.txt

    If you block GPTBot, ClaudeBot, PerplexityBot and Google-Extended in your robots.txt, you have opted out of being cited. It’s that direct. And most stores that block those crawlers didn’t choose to — it was a default from a security plugin, a Cloudflare preset, or a hardening file that someone copied from a blog post in 2023.

    Open your /robots.txt, grep for those four user-agents, and if any of them is disallowed, undo it. Then add an llms.txt at the site root: a small flat index of the canonical URLs you most want agents to read.

    Honest footnote: llms.txt is still an emerging convention, less universally respected than robots.txt or sitemap.xml. The cost of adding one is zero and more agents respect it every quarter. I wrote more about this shift in my WordPress Day for AI talk — agents aren’t the only AI story, but they’re the readers now.

    5. Build real FAQ sections with FAQPage schema

    Of every schema type, FAQPage is the one agents cite most. It maps directly to the Q→A shape of the answer they’re trying to produce. If the store has a shipping page, a returns page, a size guide — each should be marked up. If products have common support questions (fit, materials, compatibility, care) — each should be too.

    Not SEO-filler FAQ. Real questions, from real support tickets, with direct short answers. Keep the question under 100 characters. Keep the answer under 300. No hedging. No “it depends, contact support”. If it depends, write the two cases as two questions.

    6. Don’t hide the content behind modals, cookie walls, or popups

    Agents don’t dismiss your newsletter modal. They don’t click “accept” on your cookie wall. They don’t choose a region on your geo-redirect. Whatever the HTML looks like with those overlays in the way is what gets read.

    A cookie banner at the bottom of the screen is fine. A cookie wall that blocks the main content until clicked is not. Nor is a modal that opens on load over the product name. Nor is a “verify your age” interstitial for a product that isn’t age-restricted. These are patterns people add for conversion reasons that silently cost them citability.

    • Cookie wall — main content not visible until consent. Switch to a banner.
    • Auth wall on product detail pages. Expose a public preview.
    • Geo-redirect on load that rewrites the URL. Serve the main locale and offer a switcher.
    • Newsletter overlay on first paint. Delay it, or kill it.
    • Infinite-scroll catalogue without SSR — the first 20 products exist, the other 980 don’t, from the crawler’s view. Paginate.

    The simplest verification: run curl -A "GPTBot" https://your-store.com/products/some-product and look at what comes back. If the product name and the price aren’t in that HTML, they’re not in the agent’s answer either.

    7. Keep URLs stable and canonical

    Agents remember URLs. When a model cites your product page in January and you ship a redesign in March that moves every /products/* to /shop/items/*, the citation goes to a 404 and your authority starts from zero. Keep permalinks permanent. If you must change them, 301 the old ones; don’t let the old URL break.

    On every product page, set rel="canonical" to the final clean URL — no ?utm_source=…, no ?sort=price, no ?color=blue variant. Faceted navigation (size, colour, price filters) should not spawn an infinite number of indexed URLs; each facet variant either canonicalises back to the primary or carries noindex.

    The classic way this breaks: product URLs that embed an auto-generated database ID. Migrate the store, the IDs regenerate, every cite in the wild becomes a 404. If you can’t change the URL structure, at least don’t let the ID regenerate.

    Where to start this week

    If you’re reading this at 11pm and want the order that moves the needle fastest: ship Product + Offer JSON-LD on every product page if it isn’t there already — that’s the biggest single unlock and it can land in a day. Then audit robots.txt and confirm the four agent crawlers aren’t blocked — a one-minute check. Then rewrite the top five product descriptions as facts, not as adjectives — one evening. Everything else fits a two-week sprint.

    The compounding is real. Every month your store is set up right, more agents cite you, and more of the shopping questions in your category have you in the answer. The window to be the default source in your niche is still open, but it is closing as more stores wake up to this. Weekends matter.

  • Semantic search using AI, for Framer sites

    Framer’s built-in search component matches substrings. A visitor types “sustainable sneakers”, your product is called “eco-friendly trainers”, the results panel is empty. The page loads fine, the visitor leaves, and nothing in your analytics tells you what happened.

    Swapping that out for a semantic layer is a small amount of specific work. This is what it looks like on a Framer site.

    Why substring search quietly loses sales

    Substring match is cheap, instant, and only ever finds exactly the words the author happened to write. It cannot see synonyms. It cannot see translations. It cannot see intent. On a small marketing site that is fine, because people mostly navigate. On a site with any kind of catalogue – products, articles, case studies, talks – it starts to leak.

    Semantic search fixes exactly that gap: it compares the meaning of the query to the meaning of each item, by turning both into vectors with an embeddings model. Cosine similarity between those vectors is your score. It does not replace keyword match – you still want “Model 3” to pin exactly – but it is what you reach for when the visitor speaks their own language, not yours.

    The three pieces

    You need three small things working together:

    • An indexer that reads your Framer CMS, turns each item into an embedding, and stores it somewhere you can query.
    • A search endpoint that takes a user query, embeds it, and returns the top matches by cosine similarity.
    • A Code Component on your Framer site that talks to that endpoint and renders the results.

    None of these are large. The whole thing lives in a few hundred lines.

    Indexing the CMS

    Framer exposes CMS collections as JSON at a public URL – the same one the site uses to render itself. You read it, feed each item’s text through an embeddings model, and store the resulting vector against the item’s id. Do this on a schedule, or on a webhook if your workflow has one.

    Pick a small embeddings model – text-embedding-3-small is 1536 dimensions, costs almost nothing, and is more than accurate enough for a marketing-site catalogue. Store the vectors anywhere you can list and compare them: a single JSON file in R2, a Supabase table with pgvector, a KV namespace keyed by item id. For sites below a few thousand items the simplest thing – a flat array in memory – will outperform anything fancier.

    The search endpoint

    At query time you embed the incoming query with the same model, score it against every stored vector, sort, return the top few. Cosine similarity reduces to a dot product when both vectors are L2-normalised, which is the first micro-optimisation worth doing.

    The threshold is the one knob you will revisit. Too low and unrelated items start creeping in. Too high and the search feels empty. For a marketing catalogue, somewhere between 0.30 and 0.45 usually lands.

    The Code Component

    Framer lets you drop a React component onto the canvas. For search, you want a debounced input, an AbortController so stale responses do not overwrite fresh ones, and a small results panel that renders whatever shape you returned.

    Two details that matter more than they look. Debounce at ~200ms: anything less and you pay for every keystroke, anything more and the search feels sluggish. And abort in-flight requests on every new keystroke, otherwise a slow response for “sus” will land after “sustainable sneakers” and briefly overwrite the correct results.

    Where this breaks

    Semantic search is not a free upgrade. Three things to be honest about.

    Exact matches still matter. If someone types a SKU or a product name verbatim, you want that result pinned first, not ranked 0.78 behind something fuzzier. Keep a keyword pre-pass; only fall back to vectors when it returns nothing – or use both, and merge, with keyword matches on top.

    Latency compounds. The embeddings call for the query is a network round-trip. If your endpoint lives on the other side of the planet, 150ms feels like a long time. Co-locate the endpoint with the visitor if you can; cache popular queries if you cannot.

    CMS drift. Nothing is worse than semantic search that confidently returns an item that no longer exists. Your indexer has to run often enough that deletes and renames propagate – or the endpoint has to re-validate hits against the live collection before returning them.

    The shortcut

    The snippets above are the whole pattern – if you want to own it end to end, that is all you need. If you do not, I have packaged exactly the three pieces into AI Search for Framer, on the Framer Marketplace. You install it, point it at your CMS collection, and it handles the indexer, the embeddings endpoint, and the Code Component that renders the results. One threshold slider is the only knob, and it reindexes automatically when the CMS changes.

    Either way, the thing worth internalising is the shape: embeddings turn “words your visitors use” and “words you wrote” into vectors in the same space, cosine similarity scores how close they are, and everything else is plumbing.

  • AI isn’t just agents: my talk at WordPress Day for AI 2026

    On October 24, 2026, Portugal hosted its first WordPress event dedicated entirely to AI. I was one of six featured speakers and had a 15-minute slot on the technical track to argue a quiet point: agents are not the only shape AI takes in WordPress — and vector embeddings deserve a lot more airtime than they get. Here’s the talk, the slides, the recording, and why I think this is where most WordPress site owners should start.

    The event

    WordPress Day for AI Faro 2026 ran on Saturday, October 24, 2026 at the AP Eva Senses hotel in Faro, Portugal. It was organised by Ruben Martins, Alvaro Gois, Marco Almeida, Fellyph Cintra and Jose Freitas — and, as The Repository reported, it was the first WordPress event in Portugal built entirely around artificial intelligence. Two parallel tracks, around a hundred attendees, one day.

    I was one of six featured speakers on the WPFolks lineup, alongside Sofia Correia, Lucas Catao de Moraes, Marcel Schmitz, Filipa Freitas and Jamie Marsland — a mix of WordPress agency perspective, developer tooling, and the broader “what does AI actually mean for publishing” conversation.

    My talk: AI isn’t just agents

    My session ran from 12:30 to 12:45 on the technical track. Fifteen minutes is tight, but it was enough to make one argument: the “AI in WordPress” conversation has become dominated by chatbots and agents, and that’s leaving a huge, boring, extremely useful piece of the stack out of the picture.

    Vector embeddings are the opposite of a chatbot. There’s no persona, no streaming reply, no “please wait while I think”. You take a piece of text, turn it into a 1,536-number vector that encodes its meaning, and from then on you can compare meanings mathematically. That’s it. From that one primitive, you unlock a lot:

    • Semantic search on your WordPress site. A visitor types “cheap trainers for the gym” and finds your “Nike Pegasus running shoes under 90€” page — not just posts that happen to contain the exact word trainers.
    • Content discovery that actually works. “Related posts” that are related by meaning, not just by category.
    • Smarter product recommendations. Suggestions that follow intent instead of SKU codes.
    • Multilingual retrieval for free. The same vector space understands “running shoes” and “sapatilhas de corrida” are the same thing.

    None of this needs an agent. None of it streams. It costs a fraction of a cent per piece of content indexed, and it runs sub-30 milliseconds once it’s wired up.

    Why I keep coming back to this

    Agents are impressive. They’re also hard to make reliable, expensive to run at scale, and overkill for most of the places WordPress site owners actually want “a bit of AI”. A vector-embeddings pipeline sits quietly in that 90%: a one-time index of your content, and from then on it just answers queries fast.

    I spent the last year building AI Search — the plugin I demoed on stage — to make this accessible to WordPress site owners without needing to touch an embedding API or a vector database. If you’re curious about the engineering behind it, I’ve written about it in depth at AI Search: WordPress Search with AI Embeddings.

    If you’re a WordPress developer or a shop owner reading this: this is where I’d point your attention first, before you build an agent.

    Resources

  • Do the slow work after the page is sent: WordPress’s shutdown hook

    Last month I added a search log to my WordPress plugin: every time the AI layer surfaced a product that plain keyword matching had missed, I wanted a row in a table saying so. Useful feature. Also a great way to make every single search on someone’s store slower, if you write it the obvious way.

    The fix is a WordPress hook that does not get talked about enough: shutdown.

    The problem with the obvious version

    You are already inside the search filter, you have the data, so you write the row there:

    It works. It is also bookkeeping that the shopper is paying for with their time. One INSERT is a millisecond or two, which sounds like nothing until you remember that this runs on every search, that the database might be on another host, and that your “one small write” has a way of becoming three writes and a lookup six months later.

    The visitor needs the search results. They do not need your analytics.

    What the shutdown hook actually is

    shutdown is the last action WordPress fires. Core registers it as a PHP shutdown function, so it runs at the very end of the request – after the template has rendered, after the response has been handed off. It fires on normal page loads, on AJAX, on REST requests, and even when something calls wp_die().

    That makes it the natural home for work that must happen during a request but that nobody is waiting for.

    Why it feels instant: fastcgi_finish_request()

    On PHP-FPM – which is what most decent hosting runs – PHP can tell the web server “I am done, send it” and keep executing. WordPress core and various plugins call fastcgi_finish_request() at the end of a request, so by the time your shutdown callback runs, the browser has already received the page and started rendering it.

    Be honest with yourself about what that means, though. The visitor is not waiting, but the PHP worker still is. You have moved the cost off the perceived page load and onto your pool of workers. That is a very good trade for a single INSERT. It is a terrible trade for something that takes two seconds, because under traffic you will run out of workers and the queue will bite you in a much less obvious way.

    On old mod_php or CGI setups the connection may not be closed early at all, so the technique degrades to “same total time, tidier code”. Nothing breaks – it just stops being a performance win.

    The pattern, in three moves

    This is the actual code from AI Search 1.31.0, trimmed for reading. First, register the hook where you register the others:

    Second, during the request you only collect. No queries, no writes – just put what you know on the object and carry on:

    Third, the callback that actually writes. Note the early return and the null: this thing must be safe to call when there is nothing to do, and safe to call twice.

    That is the whole trick. The search path does zero database work for logging; the row still lands on every relevant request; and the shopper never waits for it.

    When you should not reach for it

    • Anything the response depends on. Obvious when written down, easy to forget at 11pm. If the page needs the result, it cannot happen after the page.
    • Anything slow. Calling an external API, resizing images, sending mail through a slow SMTP server – all of these hold a worker hostage. That is what WP-Cron, or a real queue, is for.
    • Anything that needs to output. Headers are long gone. No redirects, no cookies, no printing. If you echo something here you will either see it glued to the end of your page or nowhere at all.
    • Anything that must not be lost. A fatal error, a killed worker or an aggressive timeout can end the request before your callback runs. For a search log that is fine. For an order, it is not.

    Small gotchas worth knowing

    $wpdb is still perfectly alive at this point, so queries work normally. Object cache writes, on the other hand, are mostly pointless: nothing else in this request will read them. And if you use a persistent object cache, remember that other requests may already be serving cached output that does not know about your write – so do not use shutdown to fix up something the current page displayed incorrectly.

    Also, keep the callback idempotent. In unusual flows (some AJAX handlers, some error paths) you can end up with the shutdown sequence running more than once. Nulling the pending payload after reading it, as above, is the cheapest possible insurance.

    The result in practice

    In AI Search this powers the Insights tab: store owners can see which searches the AI actually rescued – the queries where semantic matching surfaced products that keyword matching had missed – without the logging costing their shoppers anything. Same feature, same data, moved a few milliseconds to the right in the request lifecycle.

    It is a small technique. But “does this actually need to block the response?” is a question worth asking about half the code in a typical plugin, and shutdown is the tool for the times when the answer is no.

  • Don’t paste your passwords into Claude (do this instead)

    Last week I gave an AI agent admin access to a live WordPress site – on purpose, and without ever showing it my password. Here’s what I learned about doing this properly, including the two things that went wrong and the one time the AI refused to do what I asked. All of it is a lesson.

    The setup

    I’ve been using Claude Code to work on AI Search, my WordPress plugin, and on its marketing site. At some point the natural next step was obvious: I wanted the agent to edit the site directly – rewrite pages, create content, manage settings – instead of me copy-pasting everything it produced.

    That means giving an AI credentials to a production website. Most people do this the worst possible way: they paste their admin password straight into the chat. Please don’t. Here’s the thing about a chat conversation: you don’t control where that text goes, how long it’s retained, or what other tooling sees it. A password pasted into any chat – AI or otherwise – should be considered burned.

    What we did instead

    1. An Application Password, not my real password. WordPress has had Application Passwords built in since 5.6, and they’re made exactly for this. They only work over the REST API – they can’t be used to log into wp-admin – and each one is a separate credential you can revoke without touching your real password. One click in Users → Profile → Application Passwords and the agent’s access is gone, while yours is untouched.

    2. A local file, outside any git repository. The agent needs to read the credential somehow. We put it in a plain text file on my desktop – deliberately outside every project folder – so there was zero chance of it being committed to a repository. If a secret is anywhere near a git repo, sooner or later it ends up in one. The file’s location was mentioned in chat; its contents never were.

    3. Least privilege, named access. Name the application password after who’s using it (“claude”), so when you look at your access list in six months you know exactly what it is and whether it should still exist. And give the underlying user only the role the job needs – an Editor role is enough for content work; save Administrator for when settings genuinely need changing.

    4. Revoke when the work pauses. An unused credential is pure risk. When the project goes quiet, revoke it. Making a new one next time costs thirty seconds.

    What went wrong (and taught me things)

    The CDN ate the Authorization header. Our first attempts failed with a misleading “not logged in” error. The password was fine – the hosting CDN was stripping the Authorization header before it ever reached WordPress. The diagnosis was interesting in itself: a wrong password should produce a different error than a missing one, and it didn’t, which told us WordPress never saw the credential at all. The fix was passing the credential under a custom header name that the CDN leaves alone, restored server-side by a small snippet. Lesson: when API auth fails mysteriously, suspect the infrastructure between you and the application before suspecting the password.

    The stale password. Later, everything worked except authentication – headers arriving, HTTPS detected, and still rejected. The application password in the file simply wasn’t the one in WordPress anymore. Regenerating it fixed everything in a minute. Lesson: application passwords are shown once; if there’s any doubt about a copy-paste, don’t debug – regenerate.

    The time the AI said no

    At one point I asked the agent to clean up a leftover diagnostic endpoint. The code snippet that contained it was locked to its author (me), so the agent couldn’t edit it directly – and when it tried to route around that restriction from a different snippet, its own safety layer stepped in and blocked the action, telling it to stop and explain the situation to me instead.

    Which it did. I made the one-line edit myself in thirty seconds.

    I want to highlight this because it’s the opposite of a failure. An agent that will happily engineer its way around access controls is an agent you can’t trust with credentials at all. The boundary held, the human was informed, and the work still got done – with the right person doing the sensitive part. That’s exactly the division of labour you want.

    The checklist

    If you’re going to let an AI agent work on your WordPress site – and honestly, it’s worth it – do it like this:

    • Never paste real passwords into any chat. Anywhere. Ever.
    • Use Application Passwords (or scoped API tokens on other platforms). They’re revocable, auditable, and can’t open wp-admin.
    • Keep the credential in a local file outside your repositories, and reference the file, not the secret.
    • Name the credential after its user and grant the minimum role that does the job.
    • Expect infrastructure weirdness – CDNs and security layers love to strip auth headers. Test with a deliberately wrong credential: if the error doesn’t change, your password isn’t the problem.
    • Revoke on pause, regenerate on doubt.
    • Prefer agents with working guardrails. The refusal is a feature. If your agent never says “I shouldn’t do this – you do it”, that’s not convenience, that’s exposure.

    The result of all this? Over a few days, the agent shipped three plugin releases, rebuilt the marketing site, built a live demo, and translated the entire admin into three languages – and at no point did it know my password, and at any moment I could cut its access with one click. That’s the deal you want: full productivity, revocable trust.

    I build and customize AI-powered search for WordPress and WooCommerce. If you’re thinking about this kind of setup for your own project, let’s talk.

  • Is AI Search plugin close to Production-Ready?

    Remember when I first wrote about building an AI-powered WordPress search with embeddings? Back then, I was excited about the concept, but I was aware there was a thin line between a proof-of-concept and something you’d want to run on a real site.

    Well, a few months and several user complaints later, I’ve learned a lot about what it takes to make AI search actually work in production. Here’s what I’ve been fixing and why.

    Reality Check

    When I first shipped AI Search, I was focused on the cool tech like embeddings, cosine similarity, semantic understanding. The code worked, but I made some classic engineer mistakes:

    On a site with 50 posts? No problem. On a site with 5,000 posts? Users started complaining about 10-second page loads.

    The Service Registration Problem

    The biggest issue was embarrassingly simple. I was calling our external embedding service during __construct(), which meant every single page load triggered an API call:

    Users were getting 20-second page loads because my plugin was trying to register with our service on every request, and my service wasn’t online for months (for some reason).

    The fix: Move registration to only happen when users actually save their settings (only admin page consuming). Revolutionary, I know.

    The Search Performance Issue

    Remember that numberposts => -1 from earlier? That was pulling every post into memory, calculating embeddings for all of them, just to return maybe 10 results. On larger sites, this was doing thousands of similarity calculations per search.

    I had to rethink the entire approach:

    • Added result caching (search results are cached for 5 minutes)
    • Limited the scope of posts we process
    • Added early exit conditions

    The difference? Search went from 3-8 seconds to sub-second on most sites.

    Cache Management: Learning from Users

    One thing I didn’t anticipate was how much users would want control over their embedding data.

    So I built a proper cache management interface. Three levels of control:

    1. Clear cache only – Safe, embeddings regenerate automatically
    2. Clear post embeddings – Nuclear option, requires manual regeneration
    3. Clear everything – Start fresh (with appropriate warnings)

    Plus real-time stats showing exactly what’s cached and how much space it’s using.

    Similarity Threshold Refactoring

    In my original post, I mentioned needing a similarity threshold but didn’t really dive into the practical implications. Turns out, this was more important than I thought.

    Initially, I had the range set to 0.0-1.0 with 0.01 precision. But users kept getting irrelevant results with lower thresholds. After analyzing actual usage patterns:

    • Values below 0.5 rarely returned useful results
    • Users needed finer control for their specific content types
    • The difference between 0.750 and 0.753 can be significant for some use cases

    New approach: 0.5-1.0 range with 0.001 precision. Much better real-world results.

    What’s Actually Next

    I’m not done. The roadmap includes:

    • Search analytics – Understanding what people search for
    • Better content support – Custom fields, taxonomies, media
    • API endpoints – For headless setups and external integrations
    • Background processing – For sites with massive content volumes

    The Real Takeaway

    The technical implementation of embeddings and cosine similarity was the easy part. The hard part was making it work reliably for real users on real sites with real constraints.

    If you’re building AI-powered features, spend as much time thinking about edge cases, performance, and user control as you do about the actual AI. Your users will thank you.

    The current version (1.7.0) is what I should have shipped originally. it works, it’s fast, and it gives users the control they need. Sometimes you have to ship the MVP to learn what the actual product should be.

  • AI Search: WordPress Search with AI Embeddings

    Well, it’s been a while since my last blog post. But hey, maybe we should only write when we actually have something worth saying, right?

    This time, I do have something to share: I’ve been working on a new approach to WordPress search that uses AI and embeddings to understand the meaning behind search queries, not just the keywords.

    Let me show you how it works, and why it might completely change how your visitors interact with your content. BAsically, I built a new plugin called AI Search that brings intelligent, semantic search to WordPress.

    What Are Embeddings?

    Embeddings turn text into vector representations that capture semantic meaning. This allows us to compare how similar two texts are, even if they don’t share the same exact words.

    Then, when a user searches, their query is also embedded and compared to your content using cosine similarity.

    Here’s a visual explanation (at least, it helped me understanding the concept):

    AI embeddings

    src: https://arize.com/blog-course/embeddings-meaning-examples-and-how-to-compute/

    Those values aren’t absolute, right? So we should have a way to define how close we want our search query to be considered in our AI results – so I needed to create a method to define what is similarity in this context:

    private function calculate_similarity( $a, $b ) {
        $dot_product = array_sum( array_map( fn($x, $y) => $x * $y, $a, $b ) );
        $magnitude_a = sqrt( array_sum( array_map( fn($x) => $x ** 2, $a ) ) );
        $magnitude_b = sqrt( array_sum( array_map( fn($x) => $x ** 2, $b ) ) );
    
        return $dot_product / ( $magnitude_a * $magnitude_b );
    }

    Replacing the Search Query: From Keyword to Meaning Matching

    Out of the box, classic search is basic – not only in WordPress, in general, the search tools look for keywords. When a user types a query, WordPress looks for that exact word or phrase in post titles or content using a simple LIKE '%searchterm%' SQL clause. While this works for surface-level matching, it has major limitations:

    • It can’t understand synonyms or variations (e.g., “car” vs. “vehicle”)
    • It doesn’t grasp intent or context
    • It returns results based on text presence, not text relevance

    Let’s say you have a post titled “How to Start a Blog”. A user searching for “create a website” won’t see that post, even though it’s exactly what they need.

    With AI Search, we replace the default search behaviour entirely. Here’s the flow:

    1. The plugin hooks into the SQL query via the posts_request filter.
    2. It detects if the request is a search (is_search), and bypasses admin queries.
    3. It converts the user’s search term into an embedding vector using OpenAI.
    4. It loops through all published posts with saved embeddings.
    5. For each post, it calculates the cosine similarity between the query and the content.
    6. It filters out posts below the similarity threshold.
    7. It returns a custom SQL query that retrieves only relevant post IDs, in order of semantic relevance.

    Here’s the code in action (feel free to comment and recommend another approach):

    public function custom_search_query( $sql, $query ) {
        if ( ! $query->is_search || is_admin() ) {
            return $sql;
        }
    
        $search_query = sanitize_text_field( get_search_query() );
        $query_embedding = $this->get_embedding( $search_query );
    
        if ( ! $query_embedding ) {
            return $sql;
        }
    
        $posts = get_posts([
            'numberposts' => -1,
            'post_type'   => 'any',
            'post_status' => 'publish',
            'meta_key'    => '_ai_search_embedding',
        ]);
    
        $similarities = [];
    
        foreach ( $posts as $post ) {
            $embedding_json = get_post_meta( $post->ID, '_ai_search_embedding', true );
            if ( empty( $embedding_json ) ) {
                continue;
            }
    
            $embedding = json_decode( $embedding_json, true );
            $similarity = $this->calculate_similarity( $query_embedding, $embedding );
    
            if ( $similarity >= $this->similarity_threshold ) {
                $similarities[ $post->ID ] = $similarity;
            }
        }
    
        arsort( $similarities );
    
        $sorted_ids = array_keys( $similarities );
    
        if ( empty( $sorted_ids ) ) {
            return "SELECT * FROM {$GLOBALS['wpdb']->posts} WHERE 1=0"; // No match
        }
    
        $ids = implode( ',', array_map( 'intval', $sorted_ids ) );
        return "SELECT * FROM {$GLOBALS['wpdb']->posts} WHERE ID IN ($ids) ORDER BY FIELD(ID, $ids)";
    }
    

    This works under the hood. You don’t need to change your template files, query_posts, or WP_Query calls, the filter intercepts all search queries automatically.

    Why This Matters

    Well if you run a content-heavy site – a blog, knowledge base, product catalog, or membership platform. This upgrade will make search feel instant, intelligent, and intuitive.

    Users find what they mean, not just what they typed.


    Try AI Search

    The plugin is free and open-source, built with developers in mind. It uses native WordPress functions, clean PHP, and integrates seamlessly with your existing site. Let me know if you would like to see this working on other environments beyond WordPress.