Разработка AI-плагина для WordPress
AI-плагин для WordPress добавляет языковые модели в экосистему WP: генерация контента в блоке редактора, AI-чат-виджет для посетителей, автоматические SEO-метаданные, суммаризация статей. Технически это PHP бэкенд + JavaScript (React/Vanilla) фронтенд в рамках WordPress Plugin API.
Архитектура плагина
<?php
/**
* Plugin Name: AI Assistant
* Version: 1.0.0
*/
// Предотвращение прямого доступа
if (!defined('ABSPATH')) exit;
class AIAssistant {
private string $api_key;
public function __construct() {
$this->api_key = get_option('ai_assistant_api_key', '');
// Регистрируем REST API endpoint
add_action('rest_api_init', [$this, 'register_endpoints']);
// Добавляем блок Gutenberg
add_action('init', [$this, 'register_block']);
// Страница настроек
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', // Публичный endpoint для чата
]);
}
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' => 'Ты — копирайтер. Пиши SEO-оптимизированный контент для блога.',
'meta' => 'Создай SEO meta description до 160 символов.',
'summary' => 'Создай краткое резюме статьи для 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 (JavaScript)
// 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="Тема или описание контента"
value={prompt}
onChange={setPrompt}
rows={3}
/>
<Button isPrimary onClick={generateContent} disabled={loading || !prompt}>
{loading ? <Spinner /> : 'Сгенерировать'}
</Button>
{attributes.content && (
<RichText
tagName="div"
value={attributes.content}
onChange={content => setAttributes({ content })}
/>
)}
</div>
);
},
save({ attributes }) {
return <RichText.Content tagName="div" value={attributes.content} />;
},
});
Чат-виджет для посетителей
// Добавляем чат-виджет в 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 Помощник</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="Задайте вопрос..." style="flex:1;">
<button id="ai-chat-send">→</button>
</div>
</div>
</div>
<script>
// Встроенный скрипт чата
document.getElementById('ai-chat-toggle').addEventListener('click', () => {
const win = document.getElementById('ai-chat-window');
win.style.display = win.style.display === 'none' ? 'block' : 'none';
});
// ... логика отправки сообщений
</script>
<?php
});
Практический кейс: контент-агентство
Задача: агентство публикует 30+ статей в неделю. Копирайтеры тратили 30–40 мин на SEO-метаданные и структуру каждой статьи.
Плагин: кнопка "AI-помощник" в Gutenberg для генерации структуры, черновика, meta title/description.
Результат: время подготовки одной статьи: -45%. SEO-метаданные: 100% генерируются AI, редактируются вручную.
Сроки
- Базовый плагин с REST API: 3–5 дней
- Gutenberg блок: 3–5 дней
- Чат-виджет для посетителей: 3–5 дней
- WooCommerce интеграция (описания товаров): +1 неделя







