WordPress AI Plugin: REST API, Gutenberg & Chat Integration

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
WordPress AI Plugin: REST API, Gutenberg & Chat Integration
Medium
~1-2 weeks
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1360
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

Creating a Smart WordPress Plugin with AI Capabilities

Integrating ChatGPT via iframe in WordPress often leads to CORS errors. A chat widget built with jQuery slows down at 10,000 visitors, and latency p99 spikes. A typical situation: the plugin works, but the context window breaks mid-dialogue, and content generation in Gutenberg takes minutes. As AI/ML engineers, we encounter this daily.

We develop turnkey AI plugins for WordPress that solve these problems at the architecture level: PHP backend + JavaScript frontend working through the WordPress Plugin API. Our portfolio includes over 50 successful projects integrating LLMs into CMS, including RAG pipelines, chat widgets, and automatic metadata generation. Let's break down how we build AI solutions: from model selection to deployment.

What Does an AI Plugin Solve?

Content generation. Copywriters spend 30–40 minutes on SEO metadata and structure per article. A plugin with REST API and a Gutenberg block cuts that time by 45%: AI generates a draft, meta title, and description in seconds.

User chat widget. Visitors want instant answers. An LLM-based chat with an 8K token context window processes questions without overloading support. We use streaming for low latency — the answer appears as it's generated.

SEO automation. An AI plugin can generate meta descriptions up to 160 characters, pick LSI keywords, and create summaries for featured snippets. This boosts organic traffic CTR.

How Does Our AI Plugin Speed Up Copywriters?

Practical case: a content agency publishes 30+ articles per week. Copywriters spent 30–40 minutes on SEO metadata and structure per article. We implemented an "AI Assistant" button in Gutenberg to generate structure, draft, meta title, and description. We used Claude Haiku for speed and GPT-4o for complex drafts.

Result: preparation time per article reduced by 45%. SEO metadata is now 100% AI-generated but remains under manual control. API costs are minimal — less than $0.02 per article. Clients save an average of $500 per month on copywriting costs.

Why REST API Instead of Direct External API Calls?

Direct calls from JavaScript expose the API key in the browser. A REST API on PHP acts as a proxy: the key is stored server-side, and the client only receives the result. This is secure and allows caching, validation, and logging. Additionally, server-side request handling is 2× faster than an iframe solution — we measured p99 latency out of the box.

What to Consider When Choosing a Model?

Model Use Case Latency p99 Resource Requirements
Claude Haiku Chat, metadata generation 500 ms Cloud API
GPT-4o Content, translations 1.2 s Cloud API
LLaMA 3 8B Local deployment 200 ms (GPU) GPU 8GB+
Mistral 7B Budget inference 300 ms (GPU) GPU 4GB+

Architecture and Code

REST API Endpoint for Generation

The plugin registers a custom REST route (/ai-assistant/v1/generate), protected by edit capabilities. The callback handles different request types: post — article draft, meta — SEO description, summary — brief summary. The system prompt is selected based on the type.

<?php
/**
 * Plugin Name: AI Assistant
 * Version: 1.0.0
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class AIAssistant {

    private string $api_key;

    public function __construct() {
        $this->api_key = get_option('ai_assistant_api_key', '');

        // Register REST API endpoint
        add_action('rest_api_init', [$this, 'register_endpoints']);

        // Add Gutenberg block
        add_action('init', [$this, 'register_block']);

        // Settings page
        add_action('admin_menu', [$this, 'add_settings_page']);
    }

    public function register_endpoints(): void {
        register_rest_route('ai-assistant/v1', '/generate', [
            'methods'  => 'POST',
            'callback' => [$this, 'generate_content'],
            'permission_callback' => function() {
                return current_user_can('edit_posts');
            },
        ]);

        register_rest_route('ai-assistant/v1', '/chat', [
            'methods'  => 'POST',
            'callback' => [$this, 'chat_response'],
            'permission_callback' => '__return_true',  // Public endpoint for chat
        ]);
    }

    public function generate_content(WP_REST_Request $request): WP_REST_Response {
        $prompt = sanitize_text_field($request->get_param('prompt'));
        $type = sanitize_key($request->get_param('type')); // 'post', 'meta', 'summary'

        if (empty($this->api_key)) {
            return new WP_REST_Response(['error' => 'API key not configured'], 400);
        }

        $system_prompts = [
            'post' => 'You are a copywriter. Write SEO-optimized content for a blog.',
            'meta' => 'Create an SEO meta description up to 160 characters.',
            'summary' => 'Create a brief article summary for a featured snippet.',
        ];

        $response = $this->call_anthropic_api(
            $system_prompts[$type] ?? $system_prompts['post'],
            $prompt
        );

        return new WP_REST_Response(['content' => $response]);
    }

    private function call_anthropic_api(string $system, string $user_message): string {
        $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
            'headers' => [
                'x-api-key'         => $this->api_key,
                'anthropic-version' => '2023-06-01',
                'content-type'      => 'application/json',
            ],
            'body' => json_encode([
                'model'      => 'claude-haiku-4-5',
                'max_tokens' => 1024,
                'system'     => $system,
                'messages'   => [['role' => 'user', 'content' => $user_message]],
            ]),
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            throw new RuntimeException($response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        return $body['content'][0]['text'] ?? '';
    }
}

new AIAssistant();

Gutenberg Block for Content Managers

The user enters a topic in a text field, clicks "Generate" — and gets a draft directly in the editor. The block uses apiFetch to call our REST endpoint. After generation, the content is editable via RichText.

// blocks/ai-generator/index.js
import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps, RichText } from '@wordpress/block-editor';
import { Button, TextareaControl, Spinner } from '@wordpress/components';
import { useState } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';

registerBlockType('ai-assistant/generator', {
    title: 'AI Content Generator',
    category: 'text',
    attributes: {
        content: { type: 'string', default: '' },
    },

    edit({ attributes, setAttributes }) {
        const [prompt, setPrompt] = useState('');
        const [loading, setLoading] = useState(false);
        const blockProps = useBlockProps();

        const generateContent = async () => {
            setLoading(true);
            try {
                const response = await apiFetch({
                    path: '/ai-assistant/v1/generate',
                    method: 'POST',
                    data: { prompt, type: 'post' },
                });
                setAttributes({ content: response.content });
            } catch (error) {
                console.error('Generation failed:', error);
            }
            setLoading(false);
        };

        return (
            <div {...blockProps}>
                <TextareaControl
                    label="Topic or content description"
                    value={prompt}
                    onChange={setPrompt}
                    rows={3}
                />
                <Button isPrimary onClick={generateContent} disabled={loading || !prompt}>
                    {loading ? <Spinner /> : 'Generate'}
                </Button>
                {attributes.content && (
                    <RichText
                        tagName="div"
                        value={attributes.content}
                        onChange={content => setAttributes({ content })}
                    />
                )}
            </div>
        );
    },

    save({ attributes }) {
        return <RichText.Content tagName="div" value={attributes.content} />;
    },
});

Chat Widget for Visitors

The widget is loaded via the wp_footer hook. For the public chat, we use a separate endpoint without permission checks but with rate limiting. AI responds in streaming format, improving UX.

// Add chat widget to footer
add_action('wp_footer', function() {
    if (!get_option('ai_assistant_chat_enabled')) return;
    ?>
    <div id="ai-chat-widget" style="position:fixed;bottom:20px;right:20px;z-index:9999;">
        <button id="ai-chat-toggle">💬 AI Assistant</button>
        <div id="ai-chat-window" style="display:none;width:350px;height:500px;background:#fff;border:1px solid #ccc;border-radius:8px;">
            <div id="ai-chat-messages" style="height:420px;overflow-y:auto;padding:10px;"></div>
            <div style="padding:10px;display:flex;gap:8px;">
                <input type="text" id="ai-chat-input" placeholder="Ask a question..." style="flex:1;">
                <button id="ai-chat-send">→</button>
            </div>
        </div>
    </div>
    <script>
    // Inline chat script
    document.getElementById('ai-chat-toggle').addEventListener('click', () => {
        const win = document.getElementById('ai-chat-window');
        win.style.display = win.style.display === 'none' ? 'block' : 'none';
    });
    // ... message sending logic
    </script>
    <?php
});

Work Process: From Task to Deployment

  1. Analytics — identify required features: content generation, chat, SEO, personalization.
  2. Design — choose model and architecture (API or local inference).
  3. Implementation — write PHP classes, JS blocks, configure REST endpoints.
  4. Testing — cover scenarios: API errors, long prompts, load testing for chat.
  5. Deployment — install the plugin on your hosting, set up monitoring and alerts.

Timeline Estimates

Stage Duration
Basic plugin with REST API 3–5 days
Gutenberg block 3–5 days
Chat widget for visitors 3–5 days
WooCommerce integration (product descriptions) +1 week
Load testing and optimization +2 days

What's Included in Our Work

  • Plugin with required functionality (REST API, blocks, widgets).
  • Documentation for API and administration.
  • Source code with comments and license.
  • Administrator training on AI features.
  • 6 months of support (bug fixes, compatibility updates).

With over 7 years of expertise in WordPress development and more than 100 AI integrations, our team delivers reliable solutions. Our AI plugin development services start at $1,500 for a basic integration. Our custom AI plugin includes tokenization and context window management for optimal performance.

Contact us for an assessment of your project. Request a consultation on LLM integration — we'll help you choose the optimal solution. Our team has extensive experience in WordPress development and over 50 successful AI integration projects. We guarantee compatibility with the latest WP versions and the security of your data.

Useful resources: official REST API reference, overview of large language models.

LLM Development: Fine-Tuning, RAG, Agents, and Production Deployment

Using GPT‑4 or Claude 3.5 Sonnet through a public API is not a solution — it's just a tool. When the requirement is to "make it like ChatGPT, but on our data," there is a real engineering challenge behind it: from prompt engineering to training a 70B model on your own infrastructure. End-to-end LLM solution development is a complex stack, and we have been doing it for over 5 years. During this time, we have completed over 20 projects in generative AI: from RAG systems for legal departments to custom support agents. Where exactly your task falls depends on data, latency requirements, budget, and how critical confidentiality is.

A typical situation: the client has already tried ChatGPT, but results are unstable — sometimes accurate, sometimes hallucinating. Or they need integration into a corporate portal while complying with security policies. Let's break down each layer of the stack in detail — from RAG to production deployment.

Why Do RAG Systems Break and How to Fix It?

RAG (Retrieval-Augmented Generation) looks simple: find relevant documents, put them in context, get an answer. In practice, it fails in several places.

Chunking without overlap. Classic mistake: chunk_size=512, overlap=0. If the answer lies across two chunks, retrieval won't find either with sufficient confidence. Solution: overlap 15–25% of chunk_size, or better yet, sentence-aware splitting with spaCy or NLTK instead of naive character splitting.

Poor embedder. text-embedding-ada-002 is good for general use, but on legal or medical texts, specialized models like E5-large-v2, BGE-M3, or fine-tuned sentence-transformers on domain data outperform it. Recall@5 differences can be 15–25%.

No re-ranking. Vector search optimizes for speed, not relevance. A cross-encoder re-ranker (ms-marco-MiniLM-L-6-v2, bge-reranker-large) after initial retrieval improves top-3 accuracy with acceptable latency (+50–150ms). This is often more impactful than improving the embedding model.

Hybrid search. Dense vectors alone work poorly on exact queries: names, SKUs, codes. BM25 (sparse) finds exact matches but misses semantics. Hybrid via RRF (Reciprocal Rank Fusion) is the optimal compromise. Qdrant, Weaviate, and pgvector 0.7+ support hybrid search natively.

Typical production architecture for a corporate knowledge base
  1. Documents → preprocessing (PyMuPDF, Unstructured)
  2. Chunking → embedding (BGE-M3)
  3. Qdrant (hybrid dense+sparse)
  4. Cross-encoder re-ranking
  5. Context → LLM (vLLM or OpenAI API)
  6. Answer with sources (RAGAS for quality evaluation)

When to Fine-Tune Instead of Prompt Engineering?

Prompt engineering solves ~70% of LLM adaptation tasks for a domain. The remaining 30% require fine-tuning. Three indicators: the model ignores a specific output format even with detailed prompting; the task requires deep knowledge of specialized vocabulary (medicine, law); you need to significantly reduce token costs by replacing a large model with a smaller specialized one.

LoRA and QLoRA are the standard for SFT. LoRA adds trainable low-rank matrices to attention layers. A typical configuration for Llama-3 8B: r=64, lora_alpha=128, target_modules=["q_proj","v_proj","k_proj","o_proj"] yields ~0.8% trainable parameters, training on one A100 40GB. QLoRA adds 4-bit quantization (NF4) and allows fine-tuning 70B models on two A100 40GB, though speed drops by half compared to bf16.

DPO instead of RLHF. Direct Preference Optimization requires only (chosen, rejected) pairs, not scalar reward signals. DPOTrainer from the trl library (Hugging Face) implements it in a few dozen lines.

Common mistake. A dataset of 500 examples, 5 epochs, validation loss 0.8 — seems fine. But on test, the model degrades on general instructions. Cause: catastrophic forgetting. Solution: add 10–20% general instruction-following examples (Alpaca, FLAN) to the training set to preserve original capabilities.

How to Choose a Base Model: 8B or 70B?

Model Parameters Strengths Context
Llama-3.1 8B 8B Quality/speed balance 128k
Llama-3.1 70B 70B Complex reasoning 128k
Mistral 7B / Mixtral 8x7B 7B / 47B Efficiency for size 32k
Qwen2.5 72B 72B Code, multilingual 128k
Gemma 2 27B 27B Open license 8k

For most tasks, fine-tuning an 8B model is sufficient. 70B is needed when deep reasoning is required or the 8B baseline does not reach the required quality even after fine-tuning. Inference cost for Llama-3 8B via vLLM on A100 is efficient; the exact cost depends on volume.

What Does PagedAttention Bring to Production?

vLLM is the first choice for serving open-source models. PagedAttention is the key technical innovation: KV-cache is managed like virtual memory in an OS, without fragmentation. This yields 2–4x higher throughput compared to naive HuggingFace Transformers inference. The vLLM documentation confirms that continuous batching and PagedAttention are the standard for high-load LLM services.

Typical numbers on A100 80GB for Llama-3 8B (bf16): 400–600 req/s, P50 latency 200–400ms, P99 latency 600–900ms at concurrency 64. For 70B on two A100 with tensor parallelism: 80–120 req/s, P99 latency 1.5–2.5s. AWQ or GPTQ quantization reduces memory consumption by 2x with quality loss within 1–3%.

Multi-Agent Systems

Agents are LLMs with access to tools: search, code execution, API calls, database interaction. Common patterns:

  • ReAct (Reason + Act): the model reasons → chooses a tool → observes the result → reasons again. LangChain and LlamaIndex implement it out of the box.
  • Multi-agent orchestration: multiple specialized agents with a coordinator on top. Example: coordinator → researcher (search + summarization) → coder (code generation and execution) → critic (verification). Tools: AutoGen (Microsoft), CrewAI, custom implementation on LangGraph.

In production, agent systems are non-deterministic. Essential: guardrails, step limits, logging of each step, human-in-the-loop for critical actions.

How We Work: Stages, Timeline, Deliverables

Stage Duration What You Get
Audit and data collection 1–2 weeks Eval dataset of 100+ examples, task formalization
Baseline (prompt + RAG) 1–2 weeks Working prototype, quality metrics
Fine-tuning (if needed) 2–4 weeks Trained model, LoRA weights, model card
Deployment and monitoring 1–2 weeks vLLM server, Grafana + Prometheus
Documentation and training 1 week API documentation, team training

What Is Included

We deliver:

  • Technical documentation (model card, configs, deployment instructions)
  • Access to infrastructure (code repository, trained weights)
  • 1 month of post-deployment support (consultations, bug fixes)
  • Customer team training (2–3 sessions on system operation)

Timeline: basic RAG prototype — 1–2 weeks. Fine-tuning with customer data — 3–6 weeks (including data preparation). Production system with monitoring and retraining — 2–4 months. Cost is calculated individually based on data volume, model complexity, and infrastructure requirements.

We guarantee the quality of the final model with performance benchmarks and ongoing monitoring. Our engineers have hands‑on experience with dozens of production LLM systems.

Want to evaluate your project? Leave a request — we will prepare a preliminary summary within 1–2 business days. Or get a consultation on choosing the approach: RAG, fine-tuning, or hybrid — we will tell you what works best for you. Contact us to discuss your LLM development needs. Schedule a free consultation today.