Table of contents :

Keeping Your AI Data in Sync With WordPress

100-days-of-ai-harness-for-wordpress-woocommerce-with-wpsolr-017

Table of contents :

AI features are only as reliable as the WordPress data behind them. If a product description, price, stock status, or editorial update changes in WordPress but the AI search or retrieval layer still contains the old value, customers receive inaccurate answers and agencies lose confidence in the implementation.

For WooCommerce projects using WPSOLR as part of the search and retrieval stack, synchronization should be treated as a data pipeline rather than a one-time indexing task. The pipeline must detect changes, send the correct document representation, process deletions, and recover safely when an external service is unavailable.

Define the system of record

Start by documenting which system owns each field. In most WordPress and WooCommerce implementations, WordPress is the system of record for published content, while WooCommerce is the system of record for catalog and order-related data. An AI index, vector store, cache, or retrieval service should be considered a derived representation.

  • Posts and pages: title, content, excerpt, permalink, author, taxonomy terms, publication status, and modified date.
  • Products: name, description, short description, SKU, attributes, categories, tags, prices, stock visibility, and product URL.
  • Variations: variation attributes, availability, price, and parent product relationship where variations are searchable.
  • Access metadata: language, site or tenant identifier, visibility rules, and content ownership.

Do not send every WordPress field by default. Build an explicit document schema so that private metadata, customer data, internal notes, and operational fields cannot accidentally enter an AI retrieval system.

Use stable document identifiers

Every indexed document needs a deterministic identifier. A practical identifier can combine the site, post type, and WordPress object ID:

$document_id = sprintf(
    '%s:%s:%d',
    wp_parse_url(home_url(), PHP_URL_HOST),
    $post->post_type,
    $post->ID
);

Use the same identifier for updates and deletes. Avoid generating a new random ID each time a product changes. Random identifiers create duplicates and make it impossible to remove stale versions reliably. If multilingual or multisite content is indexed separately, include the site and language context in the identifier.

Detect changes at the WordPress layer

WordPress provides save and transition hooks that can be used to schedule synchronization. For WooCommerce, product and variation saves may trigger several related updates, so the handler should enqueue work instead of performing a complete remote sync during the request.

add_action('save_post_product', function ($post_id, $post, $update) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if (wp_is_post_revision($post_id) || $post->post_status !== 'publish') {
        return;
    }

    as_enqueue_async_action(
        'my_agency_sync_product',
        array('product_id' => (int) $post_id),
        'ai-index-sync'
    );
}, 10, 3);

In production, add capability and post-type checks appropriate to the project. Action Scheduler, which is widely used in WooCommerce environments, is generally preferable to making an HTTP request directly from the editor save request. It provides queued execution, retries, logs, and better protection against timeouts.

Synchronize the final published representation

The data sent to WPSOLR or an AI retrieval service should represent what the user can actually find and view. Build the payload after WordPress has applied content filters and after WooCommerce has recalculated the relevant product values.

function build_product_document($product_id) {
    $product = wc_get_product($product_id);

    if (!$product || $product->get_status() !== 'publish') {
        return null;
    }

    return array(
        'id' => 'product:' . $product->get_id(),
        'type' => 'product',
        'title' => $product->get_name(),
        'content' => wp_strip_all_tags(
            $product->get_description() . "\n" . $product->get_short_description()
        ),
        'url' => get_permalink($product->get_id()),
        'sku' => $product->get_sku(),
        'categories' => wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'names')),
        'modified_gmt' => get_post_field('post_modified_gmt', $product->get_id()),
        'visibility' => $product->get_catalog_visibility(),
    );
}

Keep searchable text and filterable metadata separate. Product category, brand, language, stock state, and price range are often better represented as structured fields than embedded only in a text string. This allows WPSOLR queries and downstream AI retrieval to apply precise filters before generating an answer.

Handle WooCommerce changes beyond product saves

A product can change without a conventional content edit. Price updates, stock changes, imports, variation updates, scheduled sales, taxonomy changes, and bulk operations can all affect search results or AI responses.

  • Register synchronization for product and variation updates.
  • Reindex the parent product when a searchable variation changes.
  • Queue updates after imports rather than issuing one remote request per imported row.
  • Synchronize taxonomy changes when category or brand filters are part of retrieval.
  • Decide whether stock and price changes require immediate updates or can use a short queue window.
  • Process scheduled publication and sale transitions at the time the visibility or price actually changes.

For high-volume stores, use a change queue keyed by document ID. If ten events arrive for the same product within a few seconds, collapse them into one synchronization job using the newest WordPress state.

Process deletes and visibility changes

Unpublishing a product is not the same as updating its content. If a product becomes private, moves to the trash, or is excluded from catalog visibility, the derived index must remove it or mark it unavailable according to the retrieval design.

add_action('before_delete_post', function ($post_id) {
    $post_type = get_post_type($post_id);

    if (in_array($post_type, array('product', 'page', 'post'), true)) {
        as_enqueue_async_action(
            'my_agency_delete_document',
            array(
                'document_id' => $post_type . ':' . (int) $post_id,
            ),
            'ai-index-sync'
        );
    }
});

Also handle status transitions such as publish to draft and changes to product visibility. A nightly reconciliation job should compare the set of eligible WordPress documents with the indexed set. This catches missed hooks, failed queues, and records removed by imports.

Make synchronization idempotent

Jobs will be retried. Network requests may time out after the remote service has accepted the document. The synchronization operation must therefore be safe to run more than once.

  1. Build the document from the current WordPress state instead of storing a fragile event snapshot.
  2. Send a stable document ID.
  3. Use upsert semantics where supported.
  4. Include a source revision such as the WordPress modified timestamp or a content hash.
  5. Record the last successful revision and response status.

A content hash can prevent unnecessary updates:

$canonical = wp_json_encode($document, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$content_hash = hash('sha256', $canonical);

$last_hash = get_post_meta($product_id, '_ai_index_hash', true);
if (hash_equals((string) $last_hash, $content_hash)) {
    return;
}

// Submit the document to the configured WPSOLR or retrieval endpoint.
// Store $content_hash only after a confirmed successful response.

Never record a document as synchronized before the remote operation has succeeded. If the endpoint returns a rate-limit or server error, leave the job retryable and preserve enough logging to diagnose the failure.

Protect privacy and access rules

AI synchronization must respect the same publication and access rules as the site. Exclude drafts, private posts, password-protected content, customer records, order notes, user profiles, and any custom fields containing personal or confidential information unless there is a documented, lawful reason to process them.

For membership, multilingual, or multi-tenant sites, include access metadata in the document and enforce it during retrieval. Do not rely on a prompt instruction to hide restricted content. The application should filter eligible documents before content is passed to an AI model.

Monitor freshness as an operational metric

Agencies should expose synchronization health to site owners and support teams. Useful metrics include queue depth, oldest pending job, success and failure counts, retry count, last successful sync per post type, delete failures, and the age difference between post_modified_gmt and the indexed revision.

Add an administrative report that can answer practical questions: which products failed to sync, why they failed, when the last full reconciliation ran, and whether WPSOLR contains a document that is no longer eligible on the WordPress site. Test these cases in staging:

  • Edit a published product description.
  • Change a product price, stock state, category, and variation.
  • Move a product to draft or trash.
  • Restore a deleted or unpublished product.
  • Run a bulk import with repeated updates.
  • Temporarily make the remote indexing service unavailable.
  • Reprocess the queue and verify that no duplicate documents appear.

With stable identifiers, queued processing, explicit schemas, delete handling, and reconciliation, WPSOLR and the surrounding AI retrieval layer can remain aligned with the live WordPress and WooCommerce data instead of becoming a stale parallel database.

Trending posts
You might also like