LabIA Agency
English
← All publications

AI Development

Technical guide to migrating WordPress to an AI-powered Python-PHP stack

A technical guide to separating web, data, and AI, replacing plugins without losing features, and planning a verifiable migration, with code and a reference lab.

By LabIA Agency · · Updated: 30/10/2026 · 15 min reading PREPRINT

WordPress migration reference diagram to PHP, Python, MariaDB and LLMs, with small LabIA Agency logo

Your application publishes content correctly, but each new AI function ends up inside a web request: generate texts, consult documents, recalculate recommendations or process hundreds of records. The problem occurs when the user waits, PHP workers become busy, and a model provider failure interrupts an operation that should be independent. Migrating WordPress can solve some of that complexity, but changing technologies without redesigning responsibilities only spreads the same problem across more servers.

This guide presents a reference architecture for backend teams, CTOs, agencies and implementers who need to evaluate a migration from WordPress to modern PHP, Python and MariaDB. The diagrams are conceptual; the screenshots come from a local demo with dummy data. They do not represent a customer migration, a LabIA deployment or a benchmark. The objective is to have contracts, phases and acceptance criteria that you can adapt to your project.

1. From monolith to stack: separating responsibilities before choosing tools

Why an AI load changes the problem

WordPress allows you to build extensible applications and can run at scale with proper configuration. The difficulty is not that it is written in PHP: it appears when the editorial load, plugin hooks, queries and external calls share the critical path of each request. Slow inference can keep a PHP-FPM worker busy even though the database responds quickly.

WordPress migration overview: moving to an AI-powered stack
WordPress migration overview: moving to an AI-powered stack

Before replacing it, profile queries, caches, external service times and worker occupancy. The WordPress optimization guide offers a starting point. You can also keep WordPress as an editorial manager and take the AI ​​out to a standalone service. A full migration only makes sense when its benefits justify the cost of rebuilding and maintaining those capabilities.

Modern PHP: the web and transactional frontier

PHP 8.3 or higher can manage server-rendered pages, authentication, permissions, forms and APIs. Use types, services with specific responsibilities, Composer, dependency injection and PDO with prepared queries. A microframework can simplify routing; writing your own should not become the main project. Choose a maintained branch and its supported patches following the official PHP support cycle, without treating a particular minor release as a permanent recommendation.

The frontend can still be PHP generated HTML with a small JavaScript layer. Decoupling content management does not force you to adopt a SPA: separate the authenticated panel, public routes and use cases. Maintain an explicit contract for drafts, scheduled publication, revisions, languages, media, and editorial control. If you remove the editor that the client uses, you need an alternative before you retire WordPress.

Python and FastAPI: AI outside the editorial request

RAG (retrieval-augmented generation) retrieves authorized chunks and adds them to the model context to ground its response; it does not retrain the LLM. Embeddings are vector representations used to compare content by similarity. Python concentrates integration with models, embeddings, document processing and RAG. FastAPI serves typed HTTP contracts; Independent workers execute the expensive tasks. LangChain is an orchestration option, not a mandatory dependency: an official SDK and small functions may suffice. Keep an application-owned interface to change providers without rewriting the entire domain.

For long jobs, return an identifier with HTTP 202 and provide a way to query its status. The FastAPI task documentation differentiates web process tasks from solutions with workers and queues. Using async def does not convert a blocking inference or intensive computation into a distributed or durable job.

Reference architecture: browser, PHP, relational base, outbox, queue, and Python workers separated from LLM provider
Conceptual design. PHP confirms the transactional operation; AI runs through an independent path, with state and access control.

MariaDB and MySQL: related, but not interchangeable

Normalize stable entities in tables: articles, translations, users, permissions, orders and jobs. Reserve JSON for variable attributes with validation rules; do not move all the keys in wp_postmeta to an opaque column. Index the queries the application actually uses and always filter by owner or tenant when applicable.

Check engine, edition and version before designing semantic searches. MariaDB Community has added vector capabilities since 11.7, according to its vector reference. That does not imply that a MySQL 8.4 installation will offer the same approximate index. The JSON implementation is also not identical between both engines. If your version does not cover the required vector retrieval, use a specialized component with a clear contract, keeping the relational database as the source of truth.

Store the document and chunk identifiers, content version, embeddings model, dimension and permissions. When changing models, reindex in a controlled way: mixing incompatible vectors produces invalid results. A RAG must retrieve only authorized documents and provide references; the retrieved context is untrusted information, never authorization to execute instructions.

REST, gRPC and queues: contracts with limits

REST with JSON usually facilitates a first PHP–Python integration. gRPC can be useful with Protobuf contracts and specific internal communication requirements, in exchange for more infrastructure. For Redis or RabbitMQ, define persistence, acknowledgements, bounded retries, and failed-message handling: installing a broker does not guarantee that a job will never be lost or duplicated.

The outbox pattern avoids the fragile “save to SQL then publish to queue” double pass. Save the business change and the event in the same transaction; a dispatcher posts the pending items. Assume at-least-once delivery, use an idempotency key, and acknowledge the message after committing the result. Add concurrency limits, execution deadlines, traceability and a reviewable failure queue.

This reference PHP client sends a short request to an internal service configured by the team. The idempotency key must be preserved when retrying the same operation; the timeout limits the acceptance wait, not the inference time:

<?php
declare(strict_types=1);
final readonly class AiJobsClient
{
  public function __construct(
    private string $baseUrl,
    private string $token,
  ) {}
  public function enqueue(
    int $articleId, string $key
  ): array {
    $valid = preg_match(
      '/^[a-f0-9-]{36}$/iD', $key
    );
    if ($articleId < 1 || !$valid) {
      throw new
        InvalidArgumentException(
        'Invalid input'
      );
    }
    $url = rtrim($this->baseUrl, '/')
      . '/v1/jobs';
    $h = curl_init($url);
    curl_setopt_array($h, [
      CURLOPT_POST => true,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_CONNECTTIMEOUT => 2,
      CURLOPT_TIMEOUT => 5,
      CURLOPT_FOLLOWLOCATION => false,
      CURLOPT_HTTPHEADER => [
        'Content-Type: ' .
        'application/json',
        'Authorization: Bearer '
          . $this->token,
        'Idempotency-Key: ' . $key,
      ],
      CURLOPT_POSTFIELDS => json_encode(
        ['article_id' => $articleId],
        JSON_THROW_ON_ERROR
      ),
    ]);
    $body = curl_exec($h);
    $status = curl_getinfo(
      $h, CURLINFO_RESPONSE_CODE
    );
    if ($body === false ||
        $status !== 202) {
      throw new RuntimeException(
        'Acceptance not confirmed'
      );
    }
    $data = json_decode(
      $body, true, 512,
      JSON_THROW_ON_ERROR
    );
    if (!is_array($data) || !is_string(
      $data['job_id'] ?? null
    )) {
      throw new RuntimeException(
        'Invalid response'
      );
    }
    return $data;
  }
}

In production, use authenticated and encrypted transport, out-of-repository secrets, service identity, and per-resource authorization. A timeout does not prove that the server has rejected the job: query by its key before duplicating it. The example is not a substitute for a complete authentication, observability, or retry system.

2. Replace plugins without losing the business they contain

Functional Inventory: Data, Behavior, and Integrations

There is no automatic conversion of plugins to PHP classes. Inventory each active extension, its tables, hooks, scheduled tasks, endpoints, licenses and dependencies. Ask what process it resolves and who validates it. A seemingly small plugin can handle consent, synchronization with another system, or messages that no one has documented.

Classify each function as temporarily retained, rebuilt, delegated through an API, or retired. The decision depends on the total cost and the team available. Don't confuse "fewer plugins" with "fewer obligations": the new team assumes updates, copies, recovery, auditing, support and issues for everything they rebuild.

  • Yoast or other SEO: preserves URLs, titles, meta descriptions, canonical, robots, structured data, sitemap and language toggles; It is not enough to copy the visible text.
  • ACF: transforms fields and their rules into a documented schema, including repeaters, relationships, media, and serialized values. Don't assume that all metadata is simple strings.
  • Forms: rebuilds server-side validation, CSRF where applicable, antispam, limits, mail delivery, attachments and error tracking.
  • Security and Members: documents roles, capabilities, sessions, access recovery, and a second authentication factor. Do not save reversible passwords or disable controls to facilitate importing.

WooCommerce, payments and memberships: migrate states, not just rows

A store incorporates taxes, coupons, inventory, returns, shipping, and reconciliation. Orders can reside in specific high-performance storage tables; don't assume that everything is in wp_posts and wp_postmeta. Use the domain APIs or exporters compatible with the installed configuration and compare the totals against the origin.

For payments, a native integration with Stripe or another provider must use their official SDK and verify the signature of each webhook over the original body. Record processed event IDs and handle duplicate or out-of-order deliveries. A browser returning from checkout is not proof of payment. Maintain a separate state machine and reconciliation before granting access or marking an order as paid.

Do not rebuild a fiscal or subscription engine solely to remove a dependency. You can maintain commerce in a specialized system while migrating the editorial catalog or AI. Define which service owns each piece of data and prevent two systems modifying the same balance or status without a reconciliation mechanism.

3. Migration plan: four phases with evidence of exit

Phase 1. Extract, normalize and reconcile

Start with a restorable copy of the database and files, an inventory of URLs, and a capture of the versions and extensions used. Work on an isolated copy and minimize personal data from the test environment. The prefix wp_ is conventional: check the actual prefix, as well as multisite and the tables of each plugin.

The WP-CLI WXR Exporter serves content, but is not a complete copy of the entire application. This illustrative command should be run only on the prepared copy; has not been run against a real WordPress for this guide:

# Run only on the isolated WP copy.
wp export --dir=./wxr-export
  1. Extract posts, custom types, taxonomies, relationships, users, media, and additional tables required for inventoried processes.
  2. Preserve source identifiers and create a stable map between old and new records; convert time zones and encodings explicitly.
  3. Transform blocks and shortcodes using verified rules; review topic-dependent content, attachments, and internal links.
  4. Reconcile counts by type and status, relationships, amounts when they exist, and content samples. Set aside rejected records with the reason for rejection.

The attached demo standardizes a small editorial fixture. Its counts describe only that example file, not a client's processing capacity or results. The laboratory supplies a SQL schema and normalized JSON output for review; it does not import them into MariaDB.

Capture of the local demo panel with inventory of a WordPress fixture and the result of its normalization
Local laboratory functional capture: inventory and reconciliation of dummy data. The output is prepared for review, not for automatic import into production.

Phase 2. Build the PHP core and maintain editorial parity

Implement use cases, repositories, and adapters separate from the HTTP transport. Validate entries, apply server authorization, and keep transactions short. Define tests for permissions, reviews, languages, preview, and scheduling, as well as the correct publishing path. Version the schema using reproducible migrations and test restoring a copy.

This minimal schematic illustrates a listing by tenant and state with cursor paging. The index responds to that pattern; not a complete design for articles, translations or commerce:

CREATE TABLE articles (
 id BIGINT UNSIGNED AUTO_INCREMENT,
 tenant_id BIGINT UNSIGNED NOT NULL,
 legacy_wp_id BIGINT UNSIGNED NOT NULL,
 locale VARCHAR(5) NOT NULL,
 status VARCHAR(16) NOT NULL,
 slug VARCHAR(190) NOT NULL,
 title VARCHAR(255) NOT NULL,
 body LONGTEXT NOT NULL,
 PRIMARY KEY (id),
 UNIQUE KEY legacy_article (
   tenant_id, legacy_wp_id, locale
 ),
 UNIQUE KEY article_url (
   tenant_id, locale, slug
 ),
 KEY tenant_status_id (
   tenant_id, status, id
 )
) ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4;

-- Bind parameters using PDO.
SELECT id, title, slug
FROM articles
WHERE tenant_id = :tenant
 AND status = 'published'
 AND id > :cursor
ORDER BY id
LIMIT 50;

Parameters are bound with PDO, not by concatenating user data. Analyze representative distributions and use EXPLAIN to review the actual plan: Declaring an index does not guarantee that the optimizer will choose it or that it will improve all queries. Cursor paging requires stable ordering and explicit decisions about concurrent changes.

Phase 3. Integrate Python, jobs and semantic index

Start with a limited case, such as indexing a published article. Version the contract, validate the content size, and link each job to an authorized tenant. The worker splits documents, calculates embeddings, records their provenance, and publishes the new index only when it is complete. An edit or delete should invalidate the previous chunks and related caches.

Evaluate retrieval and response separately with human-reviewed questions. Semantic search is not a substitute for permissions filters, nor does an on-premises model eliminate memory, maintenance, or licensing requirements. If you need to give tools to an agent, grant minimal permissions and approval for sensitive actions. You can expand the context in our article on what is agentization.

The lab includes an acceptance and idempotency FastAPI endpoint; uses demo storage and queues jobs. It does not run a model or present mock text as an AI response. In production, replace that adapter with persistence and operable workers:

@app.post('/v1/jobs', status_code=202)
def enqueue(
    payload: JobInput,
    authorization: str = Header(),
    idempotency_key: UUID = Header(),
):
    token = os.environ.get(
        'DEMO_SERVICE_TOKEN', ''
    )
    if not token or not (
        hmac.compare_digest(
            authorization,
            f'Bearer {token}'
        )
    ):
        raise HTTPException(401)
    allowed = {101, 102, 103}
    if (payload.article_id
        not in allowed):
        raise HTTPException(404)
    return accept_demo_job(
        payload.article_id,
        str(idempotency_key)
    )
Screenshot of the demo backend showing an accepted request, its ID, and a pending job without running an LLM
Local demo backend. A "queued" status certifies acceptance, not completed generation or availability of an LLM provider.

Phase 4. Deploy, compare and rehearse the return

Enable OPcache for PHP code and verify its configuration. Redis can hold application caches or queue structures, but separate its memory, persistence, and eviction policies. Do not reuse a policy intended to discard cache on jobs that must be preserved. Use shared storage for media, connection limits, and concurrency budgets to avoid shifting saturation to MariaDB.

Deploy first in parallel and compare responses with a known set. Schedule a cutoff window or incremental synchronization with final reconciliation. Avoid improvised double writes. After accepting orders or changes in the new system, returning to the old system requires reconciling those new writes; changing DNS does not constitute a complete rollback.

  1. Check the map of permanent redirects, canonical, sitemap, hreflang and media resources before cutover.
  2. Rehearse the restore and document who decides to revert, what condition triggers it, and how new writes are preserved.
  3. Run comparable loads with hot and cold cache, including authenticated users and AI provider failures.
  4. Perform a controlled cutover, monitor errors and pending jobs, and preserve the source in read-only mode for the agreed period.
Conceptual graphic of four phases: extraction, PHP core, AI integration and deployment, each with a validation gate
Validation phase and gate graph. Block width does not represent duration, budget or measured performance.

4. Performance, viability and decision-making: what to demonstrate before migrating

Technical advantages that must be converted into metrics

Separating inferences can free web workers; a query-oriented schema can reduce database work; Removing extensions can eliminate unnecessary code. These are possible mechanisms, not a proven "drastic" reduction. LLM latency can dominate the entire process even if the page's TTFB improves.

Compare the same functionality, data, infrastructure, concurrency, and cache rules. Record TTFB p50, p95 and p99, errors, completed requests and CPU consumption. Measure memory per process and aggregate consumption: multiplying workers or adding Python can increase total RAM. For AI jobs, add time to result, queue age, retries, and cost per completed task. Replying 202 quickly does not equate to generating content faster.

Define acceptance criteria before testing. A reading improvement that downgrades publishing, payments, or permissions is not a technical victory. For RAG, include retrieval evaluation, quality of references and exposure between tenants; For an SEO migration, check URL coverage and redirects, not just a tool's score.

Scalability and security: new responsibility, not automatic guarantee

You can scale PHP and Python workers separately if sessions, files, and tasks do not depend on a local disk. The database, connections, and provider quotas are still shared limits. Adding replicas requires deciding which reads tolerate delay and how consistency is maintained.

Removing plugins eliminates their components from the request path, but introduces internal APIs, Python dependencies, secrets and risks inherent to LLMs. Maintain updates, isolation, per-resource authorization, limits, testing, and observability. An unmaintained custom CMS may be less secure than a well-run WordPress.

When to keep WordPress and when to justify the investment

  • Preserve or simplify: simple editorial blog, stable corporate site or business with no budget for ongoing development and operation.
  • Decouple first: good editorial flow with a localized AI, import or search issue that can go out to a separate service.
  • Evaluate full migration: product with a distinct business domain, intensive customization, complex permissions or AI flows whose operational cost is already measured.
  • Don't decide by volume alone: millions of requests, large tables or many plugins require diagnosis; By themselves they do not make replacement mandatory.

For agencies and freelancers, feasibility includes who will maintain the product when delivery is completed. Budget documentation, transfer, dependencies, recovery and support, in addition to initial development. The license savings may be outweighed by the cost of maintaining features that WordPress already addressed correctly.

Conclusions

The bottleneck is usually mixing journeys with different needs: transactional publishing, public reading, and AI work. Spreading them across PHP, MariaDB, and Python provides control, but does not by itself eliminate latency, maintenance, or business complexity.

A sound decision starts by inventorying, measuring and defining contracts. It then advances in phases with reconciliation, functional parity and a rehearsed rollback. Keeping WordPress as the editor, or migrating just part of it, may be the most sensible option while you gather evidence.

If you need to convert this reference architecture into a plan for your platform, request a technical evaluation from LabIA Agency. The first deliverable should be a verifiable scope: functions to maintain, data to reconcile, risks, acceptance criteria and operational responsibilities, before committing a complete rewrite.

Tags:

Comments

There are no comments yet. Dare to leave the first one!

Leave your comment