Author: Samuel Silva

  • 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.

  • Your Search Bar Is Your Back Door: And Here’s How to Lock It

    Last Saturday I spoke at WordCamp Europe 2026 in Kraków about a topic that’s been on my mind for a while: the WordPress search endpoint as a DDoS attack vector.

    The talk was called “The Hidden DDoS Threat in WordPress: Abusing the Search Endpoint“ and the response was incredible (thank you very much!!). However, some feedback came after the talk, and it pushed me to build something better.

    You can see the session here: https://europe.wordcamp.org/2026/session/the-hidden-ddos-threat-in-wordpress-abusing-the-search-endpoint/

    What the talk covered

    The core idea is simple. Every WordPress site has a search endpoint (/?s=). Unlike your regular pages, search queries bypass CDN and cache entirely. Every single search request hits your database directly with a LIKE ‘%query%’ full table scan.

    An attacker doesn’t need a botnet. Just flood /?s= with random strings and your database is on its knees.

    During the talk, I showed a live benchmark comparing DDoS attacks on cached pages versus the search endpoint. Same number of requests. Completely different results. The cached pages didn’t even make the server sweat. The search endpoint brought it down.

    Photo by Claudio Schwarz

    The solution approach and the feedback

    In the talk, I proposed using wp_create_nonce() as a first line of defense. The idea was straightforward: generate a nonce on page load, require it for search requests, and block anything without it. Bots don’t load pages, so they never get the nonce.

    The point I was making is that WordPress has had tools to mitigate this since 2006. We just don’t use them, however some people raised a valid point:

    I can JUST USE the nonce and use it in my DDoS LIKE IN THE BROWSER!
    random hacker saying correct things

    They’re right. And I appreciate that feedback. The nonce approach raises the bar and stops the simplest and automated attacks. But it’s not bulletproof. A determined attacker can work around it. So let me prepare something and bring a solution that will meet the expectations. I was so frustrated with myself that I basically started to think about a solution in Krakow yet.

    Introducing WP Search Shield

    WP Search Shield is a WordPress plugin that protects your search endpoint with two layers of defense that work together.

    Layer 1: Single-use tokens

    Instead of a WordPress nonce that lasts hours, WP Search Shield generates a unique token on every page load. This token can only be used once. The moment it’s used for a search request, it’s deleted from the database and a new one is issued.

    This means:

    • An attacker extracts the token from your HTML? It works once. That’s it.
    • They want to search again? They need to load the full page again to get a new token.
    • At that point, they’re just a regular user. DDoS over.

    Layer 2: IP rate limiting

    Even if someone finds a way to rotate tokens quickly, they’re still limited to a configurable number of searches per time window. Default is 10 searches per 60 seconds per IP.

    After that? 429 Too Many Requests.

    How they work together

    AttackWithout pluginWith plugin
    Bot hits /?s=random directlyHits database403 — No token
    Bot extracts token, sends 1000 requestsAll hit databaseFirst works, rest get 403
    Bot refreshes token each timeAll hit databaseRate limited after 10
    Real user searches normallyWorksWorks seamlessly

    The plugin handles everything automatically. It injects tokens into search forms, patches fetch() and XMLHttpRequest for REST API calls, and rotates tokens after each search. Zero configuration needed.

    It works with your existing stack

    WP Search Shield is built on WordPress transients. If you’re running Redis or Memcached (which you should be), token validation and rate limiting happen in memory. No extra database queries. No external services.

    It protects both traditional search (/?s=) and REST API search (/wp-json/wp/v2/search).

    Try it yourself

    The plugin is open source and available on GitHub:

    check it here: github.com/samuelsilvapt/wp-search-shield

    Install it, activate it, done. It works out of the box with sensible defaults.

    If you want to customize it, everything is configurable via filters:

    You can also hook into blocked requests for monitoring:

    The bigger picture

    This plugin isn’t a replacement for a CDN or a WAF. It’s a targeted fix for a specific problem that those tools can’t solve.

    Your CDN caches static content beautifully. Your object cache speeds up repeated queries. But search queries are unique by nature. They can’t be cached. And that’s exactly what attackers exploit.

    WP Search Shield closes that gap.

    chilling in a random cafe in kraków while working on the plugin

    Thank you, WCEU

    To everyone who came to the talk, asked questions, and challenged the nonce approach: thank you. You made this better. But I want to say something beyond the technical stuff.

    I reconnected with old friends I hadn’t seen in years. I made new ones over coffee, over beers, over late-night conversations about everything but WordPress. I created memories that I know I’ll carry for a long time.

    There’s something special about this community. It’s not just about work, code or plugins or themes. It’s about people who genuinely care about each other and push each other to grow. I felt that in every conversation, every handshake, every “great talk” from someone in the hallway.

    And kraków, you were unforgettable.

  • 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.

  • Everyday Efficiency: PHP 8 Techniques for WordPress Engineers

    As a software engineer navigating the daily challenges of WordPress development, embracing the latest tools and tricks is essential to staying efficient and effective. In this post, I want to share three PHP 8 tricks I incorporate into my everyday tasks as a software engineer working on WordPress projects.

    When PHP 8.0 was released, I wrote about my favourite improvements here, and you’ll see some of them in this post – however, this time those techniques are part of my day as an engineer.

    These tricks aren’t just about staying up-to-date; they’re practical enhancements that make my coding life easier and my WordPress development more streamlined. Let’s dive in!

    Easier Null Handling with “?->” Operator


    In PHP 8, there’s a cool trick called the Nullsafe Operator (?->). It helps when you’re dealing with nested objects and saves you from writing lots of null-checks. Check out this example:

    // classic one
    if ($user !== null && $user->getProfile() !== null) {
       $avatar = $user->getProfile()->getAvatar();
    } else {
       $avatar = 'default.jpg';
    }
    // With PHP 8 Nullsafe Operator
    $avatar = $user?->getProfile()?->getAvatar() ?? 'default.jpg';

    This makes your code shorter and easier to read, especially when working with WordPress objects.

    Cleaner Conditionals with “match” Instead of “switch”


    PHP 8 has a new way to handle conditions using the match expression. It’s like the old switch statement but more concise. Look at this:

    
    // Traditional switch
    switch ($status) {
    case 'published':
       $message = 'Post is live!';
       break;
    case 'draft':
       $message = 'Post is still in draft.';
       break;
    default:
       $message = 'Post status unknown.';
    }
    // PHP 8 match expression
    $message = match( $status ) {
       'published' => 'Post is live!',
       'draft'     => 'Post is still in draft.',
       'default'   => 'Post status unknown.',
    };

    Personally, I love this one! When you avoid overusing If/else statements in your code, matching labels with indexes is always a great solution – even better when you can match the index with the actual status.

    Constructor Property Promotion for Cleaner Class Definitions:

    PHP 8 introduces a streamlined way to define classes with the Constructor Property Promotion feature. This feature is a game-changer for WordPress developers, allowing for more concise and readable class definitions. It’s particularly useful when creating custom components like widgets or API responses. Instead of declaring class properties and then assigning them in the constructor, PHP 8 allows you to do both simultaneously, thereby reducing boilerplate code.

    For example, consider a custom widget in a WordPress theme:

    // PHP 7 style
    class CustomWidget {
        private $title;
        private $content;
    
        public function __construct($title, $content) {
            $this->title = $title;
            $this->content = $content;
        }
    }
    
    // PHP 8 Constructor Property Promotion
    class CustomWidget {
        public function __construct(
            private $title, 
            private $content
        ) {}
    }

    This approach makes the code significantly more concise and enhances readability, which is essential in complex WordPress projects.

    Named Arguments for More Readable Function Calls

    PHP 8’s Named Arguments feature significantly enhances the readability of function calls, especially in WordPress where functions often come with multiple parameters. This feature allows developers to pass arguments to a function based on their names, rather than their position, making the code more understandable and less prone to errors related to the ordering of arguments.

    Again, considering a WordPress function call scenario:

    // PHP 7 positional arguments
    add_theme_support('custom-background', array(
        'default-color' => '000000',
        'default-image' => '',
    ));
    
    // PHP 8 named arguments
    add_theme_support('custom-background', default-color: '000000', default-image: '');
    
    // Another example with WP_Query
    $query = new WP_Query(array(
        'post_type' => 'post',
        'posts_per_page' => 10,
        'orderby' => 'title',
        'order' => 'ASC'
    ));
    
    // With PHP 8 named arguments
    $query = new WP_Query(
        post_type: 'post',
        posts_per_page: 10,
        orderby: 'title',
        order: 'ASC'
    );

    Using named arguments not only clarifies the purpose of each parameter but also makes the code more flexible for future changes, an invaluable asset in the evolving landscape of WordPress development.

    More Control with Union Types

    PHP 8 introduces something called union types. It’s a way to say a variable can be one of several types. This is handy when working with functions that can take different kinds of data:


    // Without union types
    function processUserData($data) {
    // Function logic here
    }
    // With union types
    function processUserData( array|string $data ) {
    // Function logic here
    }


    By using union types, you can be clearer about what kind of data your functions expect, making your WordPress code more robust.

    Is WordPress core already prepared for PHP 8?

    It’s very important that you run your local PHP environment as similar as possible to your project’s final server, because although WP core is compatible with PHP, you’ll see that officially the stable version continues to be 7.4. But my advice: run at least version 8.1 🙂

    Conclusion

    These PHP 8 tricks might seem small, but they can make a big difference in your WordPress development. The Nullsafe Operator, Match Expression, and Union Types are easy to understand and implement. By using these tricks, you’ll not only stay current but also write code that’s simpler, cleaner, and more effective in your WordPress projects.

    All these details will reveal that you’re proud of your work. In a world where >40% of the Internet potentially can run your code, keep in mind you have the mission to create a web that is being designed to last.

  • PHP 8.0 – 4 new features in this latest version

    PHP 8.0 – 4 new features in this latest version

    New PHP major versions are always very expected by PHP developers, we already know good things coming when a new release is announced. This time we have a lot of performance improvements and new features that improve our code, using modern programming methods in a badass old-school language.

    Besides those new features and recommendations, I strongly recommend we use them only for environments that we can expect and have sure that 8.0 is running. In some cases, we can use polyfills instead. If you’re a plugin developer, it’s too soon to start using the new features of this version.

    Nullsafe operator

    I really love clean and efficient code, so I’m not a fan of the classic if/else statements (why we shouldn’t use them? Read more here). However, there is always a time when we need to use a simple if/then, and the best way to do that is using an inline if statement Like this:

     $today_exists = time() ? true : false;

    Clean, useful and works like a charm. I can’t know how many times I’ve tried to check a null value of a class method (for example), giving a “then” statement in the same line. Simple – it wasn’t possible, and the solution was based into split the statement into two or more lines.

    The good news is called Nullsafe operator. PHP 8 now provides a null validation without any errors, so the following example now is pretty possible:

    $today_exists = $this->get_time()?->$this->is_true();

    str_contains() function

    With this new function, we no longer need to use the strpos() function. This last one is more recognized by developers to be used to verify if a string contains a word, like this:

    $today_exists = ( false !== strpos( 'Today is the day', 'Today' ) );

    Yes, that’s what we had to do to check if a string contains X word 🙂

    Checking the documentation, it’s really strange to see str_contains() only is available from 8.0. In this link, you can also find a pollyfill alternative.

    New match() expression

    That’s a good one for clean code. Imagine we have a switch case expression, but optimized to be used without breaks, and organized as a class sintax. I’m particullary interested into starting to use this new approach, check some examples in the documentation.

    $food = 'cake';
    
    $return_value = match ($food) {
        'apple' => 'This food is an apple',
        'bar' => 'This food is a bar',
        'cake' => 'This food is a cake',
    };
    
    var_dump($return_value);

    Enums

    Exactly like other languages (e.g. javascript), enums provides us to call a function and have a definite number of cases on the args. The result is a more stable code. This one will be available in the 8.1 release only, but it’s a great example of what it’s happening with PHP – giving to the developers great native features we can use like a modern programming language.

    I’m looking forward to use these features on my code, and I’m confident that will be possible soon – PHP 8.0 has been launched in November 2020, so please read more about WordPress and 8.0 compatibility before starting to code.

  • Stock Sync – How to sync products in a WooCommerce Multisite

    There are a lot of reasons to use the Multisite feature on a WordPress environment – the challenge is when we need to synchronize information between them. Same database, but different tables, languages and product stocks are great examples of common data between all websites. Let’s start from the beginning.

    What is WordPress Multisite?

    Using the same hosting, network and dashboard, WordPress allow us to create several websites in the same place. The advantages:

    • Same plugins/version on all websites (less maintenance time);
    • Same code, different content;
    • Same themes across the websites;
    • Better content and network management;
    • Allow us to divide the websites using subdirectories (e.g. samuelsilva.pt/courses) or subdomains (e.g. courses.samuelsilva.pt);
    • Multisite means less code, literally.

    How do the same products sync on all websites?

    They don’t sync – there is no communication between websites. Each website works with different tables in the database – sometimes can be redundant, but remember – different content is the main advantage of a WP multisite environment.

    How to sync the products on the same multisite network?

    That’s why you’re here. There are many ways to sync the products, so I’ll suggest to you which I consider the best one (without plugins).

    Before anything, please check the most important WordPress functions we will use on this code snippet:

    • get_sites() – retrieves the list of the websites from our network, depending of the args we use. In this specific case, we will use the default args;
    • switch_to_blog() – sending the blog_id (site ID) as a parameter, all your further queries results will come from that specific blog;
    • restore_current_blog() – come back the queries to the main website.

    Using these functions, we will be able to create a bridge between all the websites in the multisite network. We have a lot of possibilities, but let’s focus on a specific need – synchronize stock units between websites.

    Important question: Which field will be our key (foreign key for SQL people)?

    I don’t recommend we use the most obvious – product_id. Remember, there isn’t any relationship between the websites, so we can’t trust an autoincremented field. Let’s use the product SKU in our example. Let’s go forward to our snippet:

    Stock Products between websites – code snippet

    Follow we can find my suggestion on a code snippet. If you have any questions or suggestions, please write a comment on this post.

    /* 
    * Sync products stocks by the lowest. Run this function for each product
    * @param	string	$sku	Product SKU
    */
    public function sync_stock_by_sku ( $sku ){
    
    	// Firstly, check if we're on a WP multisite environment
    	if( ! function_exists( 'get_sites' ) || $sites = get_sites() ){
    		return;
    	}
    	
    	$stores = array();
    
    	// Prepare and array with the sites Ids
    	foreach ( $this->sites as $site ) {
    
    		// Organize the multidimensional array, indexing by country code
    		$country_c 			  = str_replace( '/', '', $site->path );	
    		$stores[ $country_c ] = $site->blog_id;
    
    	}
    
    	// in this case, we will sync all the products to the lowest stock store for this specific product
    	$lowest_stock = false;
    
    	$product_id = wc_get_product_id_by_sku( $sku );
    	$product    = wc_get_product( $product_id );
    
    	// Websites loop
    	foreach( $stores as $c_code => $store_id ){
    
    		// prepare the queries to run for each website
    		switch_to_blog( $store_id );
    
    		
    
    		
    		// Continue the loop if the line item is empty, for example
    		if( ! $product ){
    			continue;
    		}
    		
    		// If this is the first product, override the lowest stock entry
    		// and continue the loop
    		if ( ! $lowest_stock && is_bool( $lowest_stock ) ) {
    			$lowest_stock = $product->get_stock_quantity();
    			continue;
    		}
    	
    		// Check if the stock from this store is lower than the current one
    		$stock = $product->get_stock_quantity();
    
    		if ( $lowest_stock > $stock ){
    			$lowest_stock = $stock;
    		}
    
    
    	}
    
    	// Now we have the lowest stock value. Let's reloop and sync stock quantity to the lowest value
    
    	foreach( $stores as $c_code => $store_id ){
    
    		// prepare the queries to run for each website
    		switch_to_blog( $store_id );
    
    		$product_id = wc_get_product_id_by_sku( $sku );
    		$product    = wc_get_product( $product_id );
    
    
    		// Update the stock quantity
    		wc_update_product_stock( $product, $lowest_stock );
    	}
    
    	// Restore queries to the current site
    	restore_current_blog();
    
    	// Return the new stock
    	return $lowest_stock;
    
    }

  • MySQL and WordPress – How to use native queries in a secure and right way

    WordPress requires a MySQL instance to run and store all the data. Although the relational system is a classic and, sometimes, obsolete data structure, MySQL works like a charm on a WordPress environment.

    Keeping this on the WordPress core, gave us better compatibility with our custom development over time and quick and easy access to the data. However, rare times developers access the data using MySQL native queries – normally, the WP methods are enough for a straightforward development (New WP_Query, get_posts, etc…). But if you need deeper access to the data, SQL Queries need to enter on your WP package-skills. High-level SQL knowledge isn’t needed, but knowing some methods will be great for your future developments.

    Consider you already have some skills using SQL statements, I would like to show you the best secure way to work with it using WordPress Best Practices. Please follow me:

    WordPress Database Class

    WordPress core already has a class to interact with the database, it’s a global object: $wpdb. Don’t ignore it, this class is the safer and better way to access the database directly. If you need to extend the class for your specific needs, you can replace it in wp-content/db.php. Anyway, I strongly suggest only use this alternative if the existing methods don’t be enough.

    Sanitize and Escape everything

    2021 and SQL injection still exists. Using $wpdb, we just need to use the “prepare” method to prevent possible SQL attacks.

    $sql = $wpdb->prepare( 'SELECT * from %s' , $table_name );

    Pretty simple and supports placeholders! After sanitizing and escaping our SQL query, we’re able to run the query.

    Query Methods

    I recommend you three main methods to run queries, depending on what you need to do with the data: consult, write, delete…

    1. get_results()
      One of my favourites, this function is used for getting an array with query results. Perfect for “SELECT” statements.
    2. get_var()
      Same as get_results(), but better for receiving a single value – a custom meta, for example. The returned value is a string, instead of an array.
    3. query()
      Use this when you need to write on the database. The function will return a true/false.

    A Complete Example

    Imagine you want to list all the WP users on an array. The best way to do that is:

    // first, call the object to be accessible
    global $wpdb;
    
    // don't forget to use the ->prefix for a dynamic table name
    $users_table = $wpdb->prefix . 'users';
    
    // your safe query
    $query      = $wpdb->prepare( 'SELECT * FROM %s', $users_table );
    $users_list = $wpdb->get_results( $query );
    

    That’s it. I recommend you read more about the $wpdb object and be prepared to write safer and more performative SQL queries on WP. Use the comments box for additional questions or suggestions!

  • WooCommerce – Save the Products’ Stock Status for each Order

    Stock Management is a default feature on all Online Store CMS, it’s useful when you manage your stock using WooCommerce, preventing out-of-stock Purchases and of course, preventing your clients’ complaints.

    Sometimes, beyond this obvious feature, we need to know some more about the stock status. For example: occasionally, for business rules’ reasons, it could be useful if we could know the stock status of the product at the date of a specific order.

    (more…)