Advertisement
[Responsive Ad - 728x90]
#AIIntegration #OpenAI #PHP8.3 #Chatbots WordPress 6.9

🤖 How to Integrate AI into WordPress 6.9 with PHP 8.3

Advanced developer guide: Build content generators, smart chatbots, automated workflows, and personalization engines using OpenAI, machine learning, and PHP 8.3's latest features.

Blogs Team

Advanced WordPress Development • 2026 Edition

⚙️ Environment Setup: PHP 8.3 + WordPress 6.9 + AI

PHP 8.3 Required: AI workloads need PHP 8.3's JIT compilation and performance improvements.

1. Server Requirements

  • PHP 8.3+ with JIT enabled (opcache.jit = tracing)
  • WordPress 6.9+
  • Composer for dependency management
  • OpenAI API key or other AI service credentials
  • Redis/Memcached for caching AI responses
  • MySQL 8.0+ or MariaDB 10.6+

2. PHP 8.3 JIT Configuration for AI

; php.ini - Optimized for AI workloads
opcache.enable=1
opcache.jit=tracing
opcache.jit_buffer_size=256M
opcache.jit=1255
opcache.enable_cli=1
opcache.revalidate_freq=0
opcache.validate_timestamps=0
memory_limit=512M
max_execution_time=300

3. Required Composer Packages

{
    "require": {
        "php": "^8.3",
        "openai-php/client": "^1.0",
        "guzzlehttp/guzzle": "^7.0",
        "predis/predis": "^2.0",
        "monolog/monolog": "^3.0",
        "symfony/cache": "^6.0",
        "league/html-to-markdown": "^5.1"
    }
}

Pro Tip: Use WordPress salts for encrypting API keys in database.

Advertisement
[Responsive Medium Rectangle - 300x250]

🔌 OpenAI Integration Framework for WordPress

Production-ready OpenAI client wrapper with caching, error handling, and WordPress integration.

OpenAI Service Class (PHP 8.3)

<?php
namespace AIWordPress\Services;

use OpenAI;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Adapter\RedisAdapter;

class OpenAIService {
    private string $apiKey;
    private $client;
    private LoggerInterface $logger;
    private $cache;
    private array $config;
    
    public function __construct(array $config) {
        $this->config = $config;
        $this->apiKey = $this->decryptKey($config['api_key']);
        $this->client = OpenAI::client($this->apiKey);
        $this->logger = wc_get_logger(); // WordPress logger
        $this->initCache();
    }
    
    private function initCache(): void {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $this->cache = new RedisAdapter($redis);
    }
    
    private function decryptKey(string $encryptedKey): string {
        // Use WordPress salts for encryption
        $key = defined('AI_ENCRYPTION_KEY') ? AI_ENCRYPTION_KEY : SECURE_AUTH_KEY;
        return openssl_decrypt(
            base64_decode($encryptedKey),
            'AES-256-CBC',
            $key,
            0,
            substr(SECURE_AUTH_SALT, 0, 16)
        );
    }
    
    public function generateContent(array $params): array {
        $cacheKey = 'ai_content_' . md5(serialize($params));
        $cached = $this->cache->getItem($cacheKey);
        
        if ($cached->isHit()) {
            $this->logger->info('AI content cache hit', ['params' => $params]);
            return $cached->get();
        }
        
        try {
            $startTime = microtime(true);
            
            $response = $this->client->chat()->create([
                'model' => $this->config['model'] ?? 'gpt-4-turbo-preview',
                'messages' => [
                    ['role' => 'system', 'content' => $params['system_prompt'] ?? ''],
                    ['role' => 'user', 'content' => $params['prompt']]
                ],
                'temperature' => $params['temperature'] ?? 0.7,
                'max_tokens' => $params['max_tokens'] ?? 2000,
                'top_p' => $params['top_p'] ?? 1,
                'frequency_penalty' => $params['frequency_penalty'] ?? 0,
                'presence_penalty' => $params['presence_penalty'] ?? 0,
            ]);
            
            $executionTime = microtime(true) - $startTime;
            $this->logger->info('AI generation completed', ['time' => $executionTime]);
            
            $result = [
                'content' => $response->choices[0]->message->content,
                'usage' => [
                    'prompt_tokens' => $response->usage->promptTokens,
                    'completion_tokens' => $response->usage->completionTokens,
                    'total_tokens' => $response->usage->totalTokens
                ],
                'model' => $response->model
            ];
            
            // Cache for 1 hour
            $cached->set($result)->expiresAfter(3600);
            $this->cache->save($cached);
            
            return $result;
            
        } catch (\Exception $e) {
            $this->logger->error('OpenAI API error', [
                'message' => $e->getMessage(),
                'params' => $params
            ]);
            
            return [
                'error' => true,
                'message' => 'AI generation failed: ' . $e->getMessage()
            ];
        }
    }
    
    public function streamContent(array $params, callable $callback): void {
        // Streaming for real-time responses
        $stream = $this->client->chat()->createStreamed([
            'model' => $this->config['model'] ?? 'gpt-4-turbo-preview',
            'messages' => [
                ['role' => 'system', 'content' => $params['system_prompt'] ?? ''],
                ['role' => 'user', 'content' => $params['prompt']]
            ],
            'temperature' => $params['temperature'] ?? 0.7,
        ]);
        
        foreach ($stream as $response) {
            $callback($response->choices[0]->delta->content ?? '');
        }
    }
}

WordPress Plugin Bootstrap

<?php
/**
 * Plugin Name: WordPress AI Suite
 * Description: Advanced AI integration for WordPress 6.9
 * Version: 1.0.0
 * Requires PHP: 8.3
 */

use AIWordPress\Services\OpenAIService;

class WordPressAIIntegration {
    private static $instance = null;
    private array $services = [];
    
    public static function getInstance(): self {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->initHooks();
        $this->loadDependencies();
    }
    
    private function initHooks(): void {
        add_action('init', [$this, 'initServices']);
        add_action('rest_api_init', [$this, 'registerRestEndpoints']);
        add_filter('cron_schedules', [$this, 'addCronSchedules']);
    }
    
    private function loadDependencies(): void {
        require_once __DIR__ . '/vendor/autoload.php';
        require_once __DIR__ . '/services/class-openai-service.php';
        require_once __DIR__ . '/chatbot/class-chatbot-handler.php';
        require_once __DIR__ . '/content/class-content-generator.php';
        require_once __DIR__ . '/personalization/class-personalization-engine.php';
    }
    
    public function initServices(): void {
        $config = get_option('ai_wordpress_config', []);
        
        $this->services['openai'] = new OpenAIService([
            'api_key' => $config['openai_api_key'] ?? '',
            'model' => $config['model'] ?? 'gpt-4-turbo-preview',
            'cache_ttl' => $config['cache_ttl'] ?? 3600
        ]);
        
        // Initialize other services
    }
    
    public function registerRestEndpoints(): void {
        register_rest_route('ai/v1', '/generate', [
            'methods' => 'POST',
            'callback' => [$this, 'handleGenerationRequest'],
            'permission_callback' => [$this, 'checkApiPermission'],
            'args' => [
                'prompt' => ['required' => true, 'type' => 'string'],
                'type' => ['required' => true, 'enum' => ['post', 'page', 'meta']]
            ]
        ]);
    }
    
    public function handleGenerationRequest($request): WP_REST_Response {
        $prompt = sanitize_text_field($request->get_param('prompt'));
        $type = $request->get_param('type');
        
        $result = $this->services['openai']->generateContent([
            'prompt' => $prompt,
            'system_prompt' => $this->getSystemPrompt($type),
            'temperature' => 0.7
        ]);
        
        return new WP_REST_Response($result, 200);
    }
    
    private function getSystemPrompt(string $type): string {
        $prompts = [
            'post' => 'You are a professional WordPress content writer. Create SEO-optimized blog posts with headings and paragraphs.',
            'page' => 'You are a web content specialist. Create compelling page content with clear structure and calls-to-action.',
            'meta' => 'You are an SEO expert. Generate meta descriptions and titles optimized for search engines.'
        ];
        
        return $prompts[$type] ?? $prompts['post'];
    }
    
    public function checkApiPermission(): bool {
        return current_user_can('edit_posts');
    }
}

// Initialize plugin
WordPressAIIntegration::getInstance();

📝 Advanced AI Content Generator

Full-featured content generator with templates, SEO optimization, and batch processing.

Content Generator Class

<?php
namespace AIWordPress\Content;

use AIWordPress\Services\OpenAIService;

class ContentGenerator {
    private OpenAIService $ai;
    private array $templates;
    
    public function __construct(OpenAIService $ai) {
        $this->ai = $ai;
        $this->initTemplates();
    }
    
    private function initTemplates(): void {
        $this->templates = [
            'blog-post' => [
                'name' => 'SEO Blog Post',
                'system_prompt' => 'You are an expert content writer. Create detailed, well-researched blog posts with proper structure, headings, and SEO optimization.',
                'structure' => [
                    'title', 'meta_description', 'introduction', 'headings', 'conclusion', 'faq'
                ]
            ],
            'product-description' => [
                'name' => 'Product Description',
                'system_prompt' => 'You are a persuasive copywriter. Create compelling product descriptions that highlight features, benefits, and drive conversions.',
                'structure' => [
                    'title', 'short_description', 'features', 'benefits', 'specifications'
                ]
            ],
            'landing-page' => [
                'name' => 'Landing Page',
                'system_prompt' => 'You are a conversion copywriter. Create high-converting landing page content with strong headlines, benefits, and CTAs.',
                'structure' => [
                    'headline', 'subheadline', 'value_proposition', 'benefits', 'testimonials', 'cta'
                ]
            ]
        ];
    }
    
    public function generateContent(array $params): array {
        $template = $this->templates[$params['template']] ?? $this->templates['blog-post'];
        
        // Build structured prompt
        $prompt = $this->buildPrompt($params['topic'], $template, $params);
        
        // Generate with AI
        $result = $this->ai->generateContent([
            'system_prompt' => $template['system_prompt'],
            'prompt' => $prompt,
            'temperature' => $params['creativity'] ?? 0.7,
            'max_tokens' => $params['length'] ?? 3000
        ]);
        
        if (isset($result['error'])) {
            return $result;
        }
        
        // Parse and structure content
        $structured = $this->parseContent($result['content'], $template['structure']);
        
        // Generate SEO metadata
        $seo = $this->generateSEO($params['topic'], $structured);
        
        // Create WordPress post
        $postId = $this->createPost($structured, $seo, $params);
        
        return [
            'post_id' => $postId,
            'content' => $structured,
            'seo' => $seo,
            'usage' => $result['usage']
        ];
    }
    
    private function buildPrompt(string $topic, array $template, array $params): string {
        $prompt = "Topic: {$topic}\n\n";
        
        if (!empty($params['keywords'])) {
            $prompt .= "Target Keywords: " . implode(', ', $params['keywords']) . "\n\n";
        }
        
        if (!empty($params['tone'])) {
            $prompt .= "Tone: {$params['tone']}\n\n";
        }
        
        if (!empty($params['target_audience'])) {
            $prompt .= "Target Audience: {$params['target_audience']}\n\n";
        }
        
        $prompt .= "Please structure the content with these sections:\n";
        $prompt .= "- " . implode("\n- ", $template['structure']) . "\n\n";
        
        $prompt .= "Make it engaging, informative, and optimized for search engines.";
        
        return $prompt;
    }
    
    private function parseContent(string $content, array $structure): array {
        $parsed = [];
        $currentSection = '';
        
        foreach (explode("\n", $content) as $line) {
            foreach ($structure as $section) {
                if (stripos($line, $section . ':') === 0 || stripos($line, '## ' . $section) === 0) {
                    $currentSection = $section;
                    $parsed[$section] = '';
                    continue 2;
                }
            }
            
            if ($currentSection) {
                $parsed[$currentSection] .= $line . "\n";
            }
        }
        
        return $parsed;
    }
    
    private function generateSEO(string $topic, array $content): array {
        $seoPrompt = "Generate SEO metadata for content about '{$topic}'. Include:\n";
        $seoPrompt .= "- Meta title (max 60 chars)\n";
        $seoPrompt .= "- Meta description (max 160 chars)\n";
        $seoPrompt .= "- Focus keyword\n";
        $seoPrompt .= "- 5 related keywords\n";
        $seoPrompt .= "- URL slug suggestion";
        
        $result = $this->ai->generateContent([
            'system_prompt' => 'You are an SEO expert. Generate optimized metadata.',
            'prompt' => $seoPrompt,
            'temperature' => 0.3
        ]);
        
        // Parse SEO response
        return $this->parseSEO($result['content']);
    }
    
    private function createPost(array $content, array $seo, array $params): int {
        $postData = [
            'post_title' => $seo['title'] ?? $params['topic'],
            'post_content' => $this->formatContent($content),
            'post_status' => $params['status'] ?? 'draft',
            'post_type' => $params['post_type'] ?? 'post',
            'post_author' => get_current_user_id(),
            'meta_input' => [
                '_ai_generated' => true,
                '_ai_prompt' => $params['topic'],
                '_yoast_wpseo_title' => $seo['title'] ?? '',
                '_yoast_wpseo_metadesc' => $seo['description'] ?? '',
                '_ai_focus_keyword' => $seo['focus_keyword'] ?? ''
            ]
        ];
        
        return wp_insert_post($postData);
    }
    
    private function formatContent(array $content): string {
        $formatted = '';
        
        foreach ($content as $section => $text) {
            if (trim($text)) {
                $formatted .= "\n

" . ucfirst($section) . "

\n\n\n"; $formatted .= "\n

" . trim($text) . "

\n\n\n"; } } return $formatted; } }

Batch Content Generator (Cron Job)

<?php
class BatchContentGenerator {
    public function __construct() {
        add_action('wp_ai_batch_generate', [$this, 'processBatch']);
        add_action('admin_menu', [$this, 'addAdminPage']);
    }
    
    public function addAdminPage(): void {
        add_submenu_page(
            'tools.php',
            'Batch Content Generator',
            'AI Batch Generator',
            'manage_options',
            'ai-batch-generator',
            [$this, 'renderPage']
        );
    }
    
    public function renderPage(): void {
        ?>
        <div class="wrap">
            <h1>Batch Content Generator</h1>
            
            <form method="post" action="">
                <?php wp_nonce_field('ai_batch_generate'); ?>
                
                <table class="form-table">
                    <tr>
                        <th>Topics (one per line)</th>
                        <td>
                            <textarea name="topics" rows="10" class="large-text"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <th>Content Template</th>
                        <td>
                            <select name="template">
                                <option value="blog-post">Blog Post</option>
                                <option value="product-description">Product Description</option>
                                <option value="landing-page">Landing Page</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th>Post Status</th>
                        <td>
                            <select name="status">
                                <option value="draft">Draft</option>
                                <option value="publish">Publish</option>
                                <option value="pending">Pending Review</option>
                            </select>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button('Start Batch Generation'); ?>
            </form>
        </div>
        <?php
    }
    
    public function processBatch(array $topics, array $params): void {
        $generator = new ContentGenerator(WordPressAIIntegration::getInstance()->services['openai']);
        
        foreach ($topics as $topic) {
            // Schedule each generation
            wp_schedule_single_event(
                time() + rand(30, 120), // Random delay between 30-120 seconds
                'wp_ai_generate_single',
                [$topic, $params]
            );
        }
        
        // Log batch job
        $this->logBatch(count($topics));
    }
    
    public function generateSingle($topic, $params): void {
        $generator = new ContentGenerator(WordPressAIIntegration::getInstance()->services['openai']);
        
        $result = $generator->generateContent([
            'topic' => $topic,
            'template' => $params['template'],
            'status' => $params['status']
        ]);
        
        if (!isset($result['error'])) {
            $this->sendNotification($result['post_id']);
        }
    }
}
Advertisement
[Responsive Leaderboard - 728x90]

💬 Building a Smart AI Chatbot with Context Memory

Advanced chatbot with conversation memory, WordPress context, and real-time streaming.

Chatbot Handler with Database Storage

<?php
namespace AIWordPress\Chatbot;

use AIWordPress\Services\OpenAIService;

class SmartChatbot {
    private OpenAIService $ai;
    private string $table;
    
    public function __construct(OpenAIService $ai) {
        global $wpdb;
        $this->ai = $ai;
        $this->table = $wpdb->prefix . 'ai_chat_sessions';
        $this->initDatabase();
        $this->registerHooks();
    }
    
    private function initDatabase(): void {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            session_id varchar(64) NOT NULL,
            user_id bigint(20),
            messages longtext NOT NULL,
            context longtext,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY session_id (session_id),
            KEY user_id (user_id)
        ) $charset_collate;";
        
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }
    
    private function registerHooks(): void {
        add_action('wp_ajax_ai_chat_message', [$this, 'handleAjaxMessage']);
        add_action('wp_ajax_nopriv_ai_chat_message', [$this, 'handleAjaxMessage']);
        add_shortcode('ai_chatbot', [$this, 'renderChatbot']);
        add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
    }
    
    public function renderChatbot($atts): string {
        $atts = shortcode_atts([
            'title' => 'AI Assistant',
            'theme' => 'light',
            'position' => 'bottom-right'
        ], $atts);
        
        $sessionId = $this->getOrCreateSession();
        
        ob_start();
        ?>
        <div class="ai-chatbot-container" data-theme="<?php echo esc_attr($atts['theme']); ?>" 
             data-position="<?php echo esc_attr($atts['position']); ?>">
            <div class="chatbot-header">
                <h3><?php echo esc_html($atts['title']); ?></h3>
                <button class="chatbot-toggle">×</button>
            </div>
            <div class="chatbot-messages">
                <div class="message bot">
                    Hello! How can I help you today?
                </div>
            </div>
            <div class="chatbot-input">
                <textarea placeholder="Type your message..." rows="1"></textarea>
                <button class="send-message">Send</button>
            </div>
            <input type="hidden" class="session-id" value="<?php echo esc_attr($sessionId); ?>">
        </div>
        <?php
        return ob_get_clean();
    }
    
    public function handleAjaxMessage(): void {
        check_ajax_referer('ai_chat_nonce', 'nonce');
        
        $message = sanitize_textarea_field($_POST['message']);
        $sessionId = sanitize_text_field($_POST['session_id']);
        $context = $this->getWordPressContext();
        
        // Get conversation history
        $history = $this->getConversationHistory($sessionId);
        
        // Build messages array
        $messages = $this->buildMessages($history, $message, $context);
        
        // Stream response
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        
        $this->ai->streamContent([
            'messages' => $messages,
            'temperature' => 0.7
        ], function($chunk) {
            echo "data: " . json_encode(['content' => $chunk]) . "\n\n";
            ob_flush();
            flush();
        });
        
        // Save to database after streaming
        $this->saveMessage($sessionId, 'user', $message);
        // Note: In production, capture the complete response
    }
    
    private function getWordPressContext(): array {
        $context = [];
        
        if (is_single()) {
            $post = get_queried_object();
            $context['current_post'] = [
                'title' => get_the_title(),
                'content' => wp_trim_words(get_the_content(), 100),
                'categories' => wp_get_post_categories($post->ID, ['fields' => 'names'])
            ];
        }
        
        if (is_user_logged_in()) {
            $user = wp_get_current_user();
            $context['user'] = [
                'name' => $user->display_name,
                'role' => implode(', ', $user->roles)
            ];
        }
        
        $context['site'] = [
            'name' => get_bloginfo('name'),
            'description' => get_bloginfo('description'),
            'url' => home_url()
        ];
        
        return $context;
    }
    
    private function buildMessages(array $history, string $currentMessage, array $context): array {
        $messages = [
            ['role' => 'system', 'content' => $this->getSystemPrompt($context)]
        ];
        
        // Add conversation history (last 10 messages)
        $recentHistory = array_slice($history, -10);
        foreach ($recentHistory as $msg) {
            $messages[] = [
                'role' => $msg['role'],
                'content' => $msg['content']
            ];
        }
        
        // Add current message
        $messages[] = ['role' => 'user', 'content' => $currentMessage];
        
        return $messages;
    }
    
    private function getSystemPrompt(array $context): string {
        $prompt = "You are a helpful AI assistant for the WordPress site: {$context['site']['name']}.\n";
        $prompt .= "Site description: {$context['site']['description']}\n\n";
        
        if (!empty($context['current_post'])) {
            $prompt .= "Current page context:\n";
            $prompt .= "- User is viewing: {$context['current_post']['title']}\n";
            $prompt .= "- Page content: {$context['current_post']['content']}\n";
        }
        
        if (!empty($context['user'])) {
            $prompt .= "User context: {$context['user']['name']} ({$context['user']['role']})\n";
        }
        
        $prompt .= "\nProvide helpful, accurate responses based on this context. If you don't know something, say so.";
        
        return $prompt;
    }
    
    private function saveMessage(string $sessionId, string $role, string $content): void {
        global $wpdb;
        
        $history = $this->getConversationHistory($sessionId);
        $history[] = ['role' => $role, 'content' => $content, 'timestamp' => current_time('mysql')];
        
        $wpdb->update(
            $this->table,
            ['messages' => json_encode($history)],
            ['session_id' => $sessionId],
            ['%s'],
            ['%s']
        );
    }
    
    private function getConversationHistory(string $sessionId): array {
        global $wpdb;
        
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT messages FROM {$this->table} WHERE session_id = %s",
            $sessionId
        ));
        
        return $row ? json_decode($row->messages, true) : [];
    }
    
    private function getOrCreateSession(): string {
        if (isset($_COOKIE['ai_chat_session'])) {
            return sanitize_text_field($_COOKIE['ai_chat_session']);
        }
        
        $sessionId = wp_generate_uuid4();
        setcookie('ai_chat_session', $sessionId, time() + DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);
        
        $this->createSession($sessionId);
        
        return $sessionId;
    }
    
    private function createSession(string $sessionId): void {
        global $wpdb;
        
        $wpdb->insert(
            $this->table,
            [
                'session_id' => $sessionId,
                'user_id' => get_current_user_id(),
                'messages' => json_encode([]),
                'context' => json_encode($this->getWordPressContext())
            ],
            ['%s', '%d', '%s', '%s']
        );
    }
    
    public function enqueueScripts(): void {
        wp_enqueue_style('ai-chatbot-css', plugins_url('assets/css/chatbot.css', __FILE__));
        wp_enqueue_script('ai-chatbot-js', plugins_url('assets/js/chatbot.js', __FILE__), ['jquery'], '1.0', true);
        
        wp_localize_script('ai-chatbot-js', 'aiChatbot', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('ai_chat_nonce'),
            'debug' => WP_DEBUG
        ]);
    }
}

Frontend JavaScript for Streaming

// assets/js/chatbot.js
(function($) {
    class AIChatbot {
        constructor() {
            this.container = $('.ai-chatbot-container');
            this.messages = this.container.find('.chatbot-messages');
            this.input = this.container.find('textarea');
            this.sendButton = this.container.find('.send-message');
            this.sessionId = this.container.find('.session-id').val();
            this.eventSource = null;
            
            this.bindEvents();
        }
        
        bindEvents() {
            this.sendButton.on('click', () => this.sendMessage());
            this.input.on('keypress', (e) => {
                if (e.which === 13 && !e.shiftKey) {
                    e.preventDefault();
                    this.sendMessage();
                }
            });
        }
        
        async sendMessage() {
            const message = this.input.val().trim();
            if (!message) return;
            
            this.addMessage('user', message);
            this.input.val('');
            this.setLoading(true);
            
            const response = await this.streamMessage(message);
        }
        
        streamMessage(message) {
            return new Promise((resolve, reject) => {
                const params = new URLSearchParams({
                    action: 'ai_chat_message',
                    message: message,
                    session_id: this.sessionId,
                    nonce: aiChatbot.nonce
                });
                
                const eventSource = new EventSource(
                    `${aiChatbot.ajax_url}?${params.toString()}`,
                    { withCredentials: true }
                );
                
                let botMessage = this.addMessage('bot', '');
                
                eventSource.onmessage = (e) => {
                    const data = JSON.parse(e.data);
                    botMessage.append(data.content);
                    this.scrollToBottom();
                };
                
                eventSource.onerror = () => {
                    eventSource.close();
                    this.setLoading(false);
                    resolve();
                };
            });
        }
        
        addMessage(role, content) {
            const messageDiv = $('<div>').addClass(`message ${role}`);
            const contentDiv = $('<div>').addClass('message-content');
            
            if (role === 'bot') {
                const typingIndicator = $('<span>').addClass('typing-indicator');
                contentDiv.append(typingIndicator);
            }
            
            contentDiv.append(content);
            messageDiv.append(contentDiv);
            this.messages.append(messageDiv);
            
            this.scrollToBottom();
            return contentDiv;
        }
        
        setLoading(loading) {
            this.sendButton.prop('disabled', loading);
            this.input.prop('disabled', loading);
        }
        
        scrollToBottom() {
            this.messages.scrollTop(this.messages[0].scrollHeight);
        }
    }
    
    $(document).ready(() => {
        new AIChatbot();
    });
})(jQuery);
Advertisement
[Responsive Large Rectangle]

🎯 AI-Powered Personalization Engine

Dynamic content personalization based on user behavior, preferences, and real-time analysis.

User Behavior Tracker

<?php
namespace AIWordPress\Personalization;

class PersonalizationEngine {
    private $ai;
    private $userProfile = [];
    
    public function __construct($ai) {
        $this->ai = $ai;
        $this->initTracking();
    }
    
    private function initTracking(): void {
        add_action('wp', [$this, 'trackPageView']);
        add_action('wp_ajax_ai_track_event', [$this, 'trackEvent']);
        add_action('wp_ajax_nopriv_ai_track_event', [$this, 'trackEvent']);
        add_filter('the_content', [$this, 'personalizeContent'], 999);
        add_filter('wp_nav_menu_items', [$this, 'personalizeMenu'], 10, 2);
    }
    
    public function trackPageView(): void {
        if (!is_user_logged_in()) return;
        
        $userId = get_current_user_id();
        $postId = get_the_ID();
        
        $this->trackEvent([
            'user_id' => $userId,
            'post_id' => $postId,
            'event_type' => 'page_view',
            'timestamp' => current_time('mysql'),
            'data' => [
                'url' => get_permalink(),
                'title' => get_the_title(),
                'categories' => wp_get_post_categories($postId),
                'tags' => wp_get_post_tags($postId, ['fields' => 'ids']),
                'time_on_page' => 0 // Will be updated via JavaScript
            ]
        ]);
    }
    
    public function trackEvent(): void {
        $event = json_decode(file_get_contents('php://input'), true);
        
        if (!$event || !wp_verify_nonce($event['nonce'], 'ai_tracking_nonce')) {
            wp_die('Invalid request');
        }
        
        $this->saveEvent($event);
        $this->updateUserProfile($event);
        
        wp_send_json_success();
    }
    
    private function saveEvent(array $event): void {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_user_events';
        
        $wpdb->insert($table, [
            'user_id' => $event['user_id'],
            'event_type' => $event['event_type'],
            'post_id' => $event['post_id'],
            'data' => json_encode($event['data']),
            'timestamp' => current_time('mysql')
        ]);
    }
    
    private function updateUserProfile(array $event): void {
        $userId = $event['user_id'];
        
        // Get existing profile
        $profile = get_user_meta($userId, 'ai_user_profile', true);
        if (!$profile) {
            $profile = [
                'interests' => [],
                'categories' => [],
                'tags' => [],
                'engagement_score' => 0,
                'preferred_time' => null,
                'content_preferences' => []
            ];
        }
        
        // Update based on event
        switch ($event['event_type']) {
            case 'page_view':
                $this->updateInterests($profile, $event);
                break;
            case 'time_spent':
                $this->updateEngagement($profile, $event);
                break;
            case 'click':
                $this->updateClickPreference($profile, $event);
                break;
            case 'purchase':
                $this->updatePurchaseHistory($profile, $event);
                break;
        }
        
        // Calculate overall engagement score
        $profile['engagement_score'] = $this->calculateEngagementScore($profile);
        
        // Generate AI-powered insights
        $profile['ai_insights'] = $this->generateInsights($profile);
        
        update_user_meta($userId, 'ai_user_profile', $profile);
    }
    
    private function updateInterests(array &$profile, array $event): void {
        if (isset($event['data']['categories'])) {
            foreach ($event['data']['categories'] as $catId) {
                if (!isset($profile['categories'][$catId])) {
                    $profile['categories'][$catId] = 0;
                }
                $profile['categories'][$catId] += 1;
            }
        }
        
        if (isset($event['data']['tags'])) {
            foreach ($event['data']['tags'] as $tagId) {
                if (!isset($profile['tags'][$tagId])) {
                    $profile['tags'][$tagId] = 0;
                }
                $profile['tags'][$tagId] += 1;
            }
        }
        
        // Keep top 20 interests
        arsort($profile['categories']);
        arsort($profile['tags']);
        $profile['categories'] = array_slice($profile['categories'], 0, 20);
        $profile['tags'] = array_slice($profile['tags'], 0, 20);
    }
    
    private function calculateEngagementScore(array $profile): float {
        $score = 0;
        
        // Weight factors
        $score += count($profile['categories']) * 2;
        $score += count($profile['tags']) * 1.5;
        $score += $profile['total_views'] ?? 0 * 0.1;
        $score += ($profile['avg_time_on_page'] ?? 0) > 60 ? 10 : 0;
        
        return min(100, $score);
    }
    
    private function generateInsights(array $profile): array {
        $prompt = "Based on this user profile, generate personalization insights:\n";
        $prompt .= "- Top interests: " . implode(', ', array_keys($profile['categories'])) . "\n";
        $prompt .= "- Engagement score: {$profile['engagement_score']}\n";
        $prompt .= "- Generate 3 content recommendations\n";
        $prompt .= "- Suggest optimal content format\n";
        $prompt .= "- Recommend best time to engage";
        
        $result = $this->ai->generateContent([
            'prompt' => $prompt,
            'temperature' => 0.3
        ]);
        
        return $result['content'] ?? [];
    }
    
    public function personalizeContent($content) {
        if (!is_singular() || !is_user_logged_in()) {
            return $content;
        }
        
        $userId = get_current_user_id();
        $profile = get_user_meta($userId, 'ai_user_profile', true);
        
        if (!$profile) {
            return $content;
        }
        
        // Get personalized recommendations
        $recommendations = $this->getRecommendations($profile);
        
        // Add personalized call-to-action
        $cta = $this->generateCTA($profile);
        
        // Insert after content
        $personalized = $content;
        $personalized .= '<div class="ai-personalized-content">';
        $personalized .= '<h3>Recommended for You</h3>';
        $personalized .= wp_kses_post($recommendations);
        $personalized .= '</div>';
        
        return $personalized;
    }
    
    private function getRecommendations(array $profile): string {
        global $wpdb;
        
        // Get top categories and tags
        $categories = array_keys($profile['categories']);
        $tags = array_keys($profile['tags']);
        
        if (empty($categories) && empty($tags)) {
            return '';
        }
        
        // Query relevant posts
        $args = [
            'post_type' => 'post',
            'posts_per_page' => 3,
            'post_status' => 'publish',
            'orderby' => 'comment_count',
            'tax_query' => []
        ];
        
        if (!empty($categories)) {
            $args['tax_query'][] = [
                'taxonomy' => 'category',
                'field' => 'term_id',
                'terms' => $categories
            ];
        }
        
        if (!empty($tags)) {
            $args['tax_query'][] = [
                'taxonomy' => 'post_tag',
                'field' => 'term_id',
                'terms' => $tags
            ];
        }
        
        $query = new WP_Query($args);
        
        if (!$query->have_posts()) {
            return '';
        }
        
        ob_start();
        echo '<ul class="ai-recommendations">';
        while ($query->have_posts()) {
            $query->the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        echo '</ul>';
        wp_reset_postdata();
        
        return ob_get_clean();
    }
    
    private function generateCTA(array $profile): string {
        $prompt = "Generate a personalized call-to-action for a user with engagement score {$profile['engagement_score']}. Make it compelling and relevant to their interests.";
        
        $result = $this->ai->generateContent([
            'prompt' => $prompt,
            'temperature' => 0.7,
            'max_tokens' => 100
        ]);
        
        return $result['content'] ?? 'Check out our latest content!';
    }
}

JavaScript Tracking Script

// assets/js/tracking.js
(function($) {
    class AITracker {
        constructor() {
            this.userId = window.aiTracking.userId;
            this.startTime = Date.now();
            this.pageId = window.aiTracking.pageId;
            
            this.trackPageView();
            this.initEventListeners();
        }
        
        trackPageView() {
            this.sendEvent('page_view', {
                url: window.location.href,
                title: document.title,
                referrer: document.referrer
            });
        }
        
        initEventListeners() {
            // Track time on page
            window.addEventListener('beforeunload', () => {
                const timeSpent = Math.round((Date.now() - this.startTime) / 1000);
                this.sendEvent('time_spent', {
                    page_id: this.pageId,
                    seconds: timeSpent
                }, true);
            });
            
            // Track clicks
            document.addEventListener('click', (e) => {
                const target = e.target.closest('a, button');
                if (target) {
                    this.sendEvent('click', {
                        element: target.tagName,
                        text: target.innerText.slice(0, 50),
                        href: target.href || ''
                    });
                }
            });
            
            // Track scroll depth
            let maxScroll = 0;
            window.addEventListener('scroll', _.throttle(() => {
                const scrollPercent = (window.scrollY + window.innerHeight) / 
                                    document.documentElement.scrollHeight * 100;
                
                if (scrollPercent > maxScroll) {
                    maxScroll = scrollPercent;
                    if (maxScroll >= 25 && maxScroll < 75) {
                        this.sendEvent('scroll', { depth: Math.floor(maxScroll) });
                    }
                }
            }, 1000));
        }
        
        sendEvent(type, data, sync = false) {
            const payload = {
                user_id: this.userId,
                post_id: this.pageId,
                event_type: type,
                data: data,
                nonce: window.aiTracking.nonce,
                timestamp: new Date().toISOString()
            };
            
            if (sync) {
                // Use sendBeacon for beforeunload
                navigator.sendBeacon(
                    window.aiTracking.ajaxUrl,
                    new Blob([JSON.stringify(payload)], {type: 'application/json'})
                );
            } else {
                $.ajax({
                    url: window.aiTracking.ajaxUrl,
                    method: 'POST',
                    data: JSON.stringify(payload),
                    contentType: 'application/json',
                    success: (response) => {
                        if (window.aiTracking.debug) {
                            console.log('Event tracked:', type, data);
                        }
                    }
                });
            }
        }
    }
    
    $(document).ready(() => {
        if (window.aiTracking) {
            new AITracker();
        }
    });
})(jQuery);

⚡ AI-Powered Automated Workflows

Create smart workflows that trigger based on events and perform AI-powered actions.

Workflow Engine

<?php
namespace AIWordPress\Workflow;

class WorkflowEngine {
    private $ai;
    private $triggers = [];
    private $actions = [];
    
    public function __construct($ai) {
        $this->ai = $ai;
        $this->registerDefaultTriggers();
        $this->registerDefaultActions();
        $this->initHooks();
    }
    
    private function registerDefaultTriggers(): void {
        $this->triggers = [
            'new_post' => [
                'name' => 'New Post Published',
                'callback' => [$this, 'triggerNewPost']
            ],
            'new_comment' => [
                'name' => 'New Comment Added',
                'callback' => [$this, 'triggerNewComment']
            ],
            'user_register' => [
                'name' => 'User Registered',
                'callback' => [$this, 'triggerUserRegister']
            ],
            'woocommerce_order' => [
                'name' => 'New Order',
                'callback' => [$this, 'triggerWooOrder']
            ],
            'form_submission' => [
                'name' => 'Form Submission',
                'callback' => [$this, 'triggerFormSubmission']
            ],
            'scheduled_time' => [
                'name' => 'Scheduled Time',
                'callback' => [$this, 'triggerScheduled']
            ],
            'api_webhook' => [
                'name' => 'Webhook Received',
                'callback' => [$this, 'triggerWebhook']
            ]
        ];
    }
    
    private function registerDefaultActions(): void {
        $this->actions = [
            'generate_content' => [
                'name' => 'Generate AI Content',
                'callback' => [$this, 'actionGenerateContent']
            ],
            'send_email' => [
                'name' => 'Send Email',
                'callback' => [$this, 'actionSendEmail']
            ],
            'update_post' => [
                'name' => 'Update Post',
                'callback' => [$this, 'actionUpdatePost']
            ],
            'create_post' => [
                'name' => 'Create Post',
                'callback' => [$this, 'actionCreatePost']
            ],
            'add_tag' => [
                'name' => 'Add User Tag',
                'callback' => [$this, 'actionAddTag']
            ],
            'api_request' => [
                'name' => 'External API Request',
                'callback' => [$this, 'actionApiRequest']
            ],
            'slack_notification' => [
                'name' => 'Send Slack Message',
                'callback' => [$this, 'actionSlack']
            ],
            'ai_analyze' => [
                'name' => 'AI Analyze Content',
                'callback' => [$this, 'actionAIAnalyze']
            ]
        ];
    }
    
    private function initHooks(): void {
        add_action('init', [$this, 'loadWorkflows']);
        add_action('wp_ai_process_workflow', [$this, 'processWorkflow'], 10, 2);
        add_action('admin_menu', [$this, 'addAdminMenu']);
        add_action('wp_ajax_ai_test_workflow', [$this, 'ajaxTestWorkflow']);
    }
    
    public function loadWorkflows(): void {
        $workflows = get_option('ai_workflows', []);
        
        foreach ($workflows as $workflow) {
            if ($workflow['active']) {
                $this->registerWorkflowHooks($workflow);
            }
        }
    }
    
    private function registerWorkflowHooks(array $workflow): void {
        $trigger = $workflow['trigger']['type'];
        
        switch ($trigger) {
            case 'new_post':
                add_action('save_post', function($postId, $post, $update) use ($workflow) {
                    if ($post->post_status === 'publish' && !$update) {
                        $this->maybeExecuteWorkflow($workflow, ['post_id' => $postId]);
                    }
                }, 10, 3);
                break;
                
            case 'new_comment':
                add_action('wp_insert_comment', function($commentId, $comment) use ($workflow) {
                    $this->maybeExecuteWorkflow($workflow, [
                        'comment_id' => $commentId,
                        'comment' => $comment
                    ]);
                }, 10, 2);
                break;
                
            case 'scheduled_time':
                if (!wp_next_scheduled('wp_ai_workflow_' . $workflow['id'])) {
                    wp_schedule_event(
                        strtotime($workflow['trigger']['config']['time']),
                        $workflow['trigger']['config']['interval'],
                        'wp_ai_workflow_' . $workflow['id']
                    );
                }
                add_action('wp_ai_workflow_' . $workflow['id'], function() use ($workflow) {
                    $this->executeWorkflow($workflow, ['scheduled' => true]);
                });
                break;
        }
    }
    
    private function maybeExecuteWorkflow(array $workflow, array $data): void {
        // Check conditions
        if (!$this->checkConditions($workflow['conditions'] ?? [], $data)) {
            return;
        }
        
        // Execute immediately or schedule
        if ($workflow['delay'] ?? 0 > 0) {
            wp_schedule_single_event(
                time() + $workflow['delay'],
                'wp_ai_process_workflow',
                [$workflow['id'], $data]
            );
        } else {
            $this->executeWorkflow($workflow, $data);
        }
    }
    
    private function checkConditions(array $conditions, array $data): bool {
        foreach ($conditions as $condition) {
            $value = $data[$condition['field']] ?? null;
            
            switch ($condition['operator']) {
                case 'equals':
                    if ($value != $condition['value']) return false;
                    break;
                case 'contains':
                    if (strpos($value, $condition['value']) === false) return false;
                    break;
                case 'greater_than':
                    if ($value <= $condition['value']) return false;
                    break;
                case 'less_than':
                    if ($value >= $condition['value']) return false;
                    break;
                case 'ai_match':
                    if (!$this->aiCheckMatch($value, $condition['value'])) return false;
                    break;
            }
        }
        
        return true;
    }
    
    private function aiCheckMatch($value, $criteria): bool {
        $prompt = "Check if this content matches the criteria: '{$criteria}'\n\nContent: {$value}\n\nRespond with YES or NO only.";
        
        $result = $this->ai->generateContent([
            'prompt' => $prompt,
            'temperature' => 0.1,
            'max_tokens' => 5
        ]);
        
        return stripos($result['content'], 'YES') !== false;
    }
    
    public function executeWorkflow(int $workflowId, array $data): void {
        $workflows = get_option('ai_workflows', []);
        $workflow = $workflows[$workflowId] ?? null;
        
        if (!$workflow || !$workflow['active']) {
            return;
        }
        
        // Log execution
        $this->logWorkflowExecution($workflowId, $data);
        
        // Execute actions
        foreach ($workflow['actions'] as $action) {
            try {
                $result = $this->executeAction($action['type'], $action['config'], $data);
                
                // Use result in next action if specified
                if ($action['output_key'] && $result) {
                    $data[$action['output_key']] = $result;
                }
            } catch (\Exception $e) {
                $this->logError($workflowId, $action, $e->getMessage());
                
                if ($workflow['stop_on_error']) {
                    break;
                }
            }
        }
    }
    
    private function executeAction(string $type, array $config, array $data) {
        switch ($type) {
            case 'generate_content':
                return $this->actionGenerateContent($config, $data);
                
            case 'send_email':
                return $this->actionSendEmail($config, $data);
                
            case 'update_post':
                return $this->actionUpdatePost($config, $data);
                
            case 'create_post':
                return $this->actionCreatePost($config, $data);
                
            case 'add_tag':
                return $this->actionAddTag($config, $data);
                
            case 'api_request':
                return $this->actionApiRequest($config, $data);
                
            case 'slack_notification':
                return $this->actionSlack($config, $data);
                
            case 'ai_analyze':
                return $this->actionAIAnalyze($config, $data);
                
            default:
                throw new \Exception("Unknown action type: {$type}");
        }
    }
    
    private function actionGenerateContent(array $config, array $data) {
        $prompt = $this->parseTemplate($config['prompt'], $data);
        
        $result = $this->ai->generateContent([
            'prompt' => $prompt,
            'temperature' => $config['temperature'] ?? 0.7,
            'max_tokens' => $config['max_tokens'] ?? 1000
        ]);
        
        return $result['content'];
    }
    
    private function actionSendEmail(array $config, array $data) {
        $to = $this->parseTemplate($config['to'], $data);
        $subject = $this->parseTemplate($config['subject'], $data);
        $message = $this->parseTemplate($config['message'], $data);
        
        return wp_mail($to, $subject, $message);
    }
    
    private function actionCreatePost(array $config, array $data) {
        $postData = [
            'post_title' => $this->parseTemplate($config['title'], $data),
            'post_content' => $this->parseTemplate($config['content'], $data),
            'post_status' => $config['status'] ?? 'draft',
            'post_type' => $config['post_type'] ?? 'post',
            'post_author' => $config['author'] ?? get_current_user_id()
        ];
        
        if (!empty($config['ai_generate'])) {
            $aiContent = $this->ai->generateContent([
                'prompt' => "Write a {$config['post_type']} about: " . $postData['post_title'],
                'temperature' => 0.7
            ]);
            
            $postData['post_content'] = $aiContent['content'];
        }
        
        return wp_insert_post($postData);
    }
    
    private function actionApiRequest(array $config, array $data) {
        $url = $this->parseTemplate($config['url'], $data);
        $method = $config['method'] ?? 'GET';
        $headers = $config['headers'] ?? [];
        $body = $this->parseTemplate(json_encode($config['body'] ?? []), $data);
        
        $response = wp_remote_request($url, [
            'method' => $method,
            'headers' => $headers,
            'body' => json_decode($body, true)
        ]);
        
        if (is_wp_error($response)) {
            throw new \Exception($response->get_error_message());
        }
        
        return wp_remote_retrieve_body($response);
    }
    
    private function actionSlack(array $config, array $data) {
        $message = $this->parseTemplate($config['message'], $data);
        $webhook = $config['webhook_url'];
        
        return wp_remote_post($webhook, [
            'headers' => ['Content-Type' => 'application/json'],
            'body' => json_encode(['text' => $message])
        ]);
    }
    
    private function actionAIAnalyze(array $config, array $data) {
        $content = $this->parseTemplate($config['content'], $data);
        $analysisType = $config['analysis_type'];
        
        $prompts = [
            'sentiment' => "Analyze the sentiment of this text (positive/negative/neutral): {$content}",
            'summary' => "Summarize this text in 2-3 sentences: {$content}",
            'keywords' => "Extract 5 key keywords from this text: {$content}",
            'category' => "Suggest a category for this content: {$content}",
            'spam' => "Check if this is spam (YES/NO): {$content}"
        ];
        
        $result = $this->ai->generateContent([
            'prompt' => $prompts[$analysisType] ?? $prompts['summary'],
            'temperature' => 0.3
        ]);
        
        return $result['content'];
    }
    
    private function parseTemplate(string $template, array $data): string {
        foreach ($data as $key => $value) {
            if (is_scalar($value)) {
                $template = str_replace("{{$key}}", $value, $template);
            }
        }
        return $template;
    }
    
    private function logWorkflowExecution(int $workflowId, array $data): void {
        global $wpdb;
        
        $wpdb->insert(
            $wpdb->prefix . 'ai_workflow_logs',
            [
                'workflow_id' => $workflowId,
                'data' => json_encode($data),
                'executed_at' => current_time('mysql')
            ],
            ['%d', '%s', '%s']
        );
    }
    
    public function addAdminMenu(): void {
        add_menu_page(
            'AI Workflows',
            'AI Workflows',
            'manage_options',
            'ai-workflows',
            [$this, 'renderAdminPage'],
            'dashicons-networking',
            30
        );
    }
    
    public function renderAdminPage(): void {
        ?>
        <div class="wrap">
            <h1>AI Workflows</h1>
            
            <div class="workflow-editor">
                <div class="trigger-selector">
                    <h3>When this happens...</h3>
                    <select id="trigger-type">
                        <?php foreach ($this->triggers as $key => $trigger): ?>
                            <option value="<?php echo esc_attr($key); ?>">
                                <?php echo esc_html($trigger['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    
                    <div id="trigger-config" class="config-panel"></div>
                </div>
                
                <div class="action-builder">
                    <h3>...do this</h3>
                    <div class="actions-list">
                        <!-- Actions will be added here -->
                    </div>
                    
                    <button class="button add-action">Add Action</button>
                </div>
                
                <div class="workflow-settings">
                    <h3>Settings</h3>
                    <label>
                        <input type="checkbox" name="active"> Active
                    </label>
                    <label>
                        <input type="checkbox" name="stop_on_error"> Stop on Error
                    </label>
                </div>
                
                <button class="button button-primary save-workflow">Save Workflow</button>
            </div>
        </div>
        <?php
    }
}

Example: Automated Content Workflow

// Example workflow configuration
$workflow = [
    'name' => 'Auto-Enhance Blog Posts',
    'active' => true,
    'trigger' => [
        'type' => 'new_post',
        'config' => [
            'post_types' => ['post'],
            'categories' => [5, 10] // Only tech categories
        ]
    ],
    'conditions' => [
        [
            'field' => 'post_title',
            'operator' => 'ai_match',
            'value' => 'contains technical content'
        ]
    ],
    'actions' => [
        [
            'type' => 'ai_analyze',
            'config' => [
                'analysis_type' => 'keywords',
                'content' => '{{post_content}}'
            ],
            'output_key' => 'keywords'
        ],
        [
            'type' => 'generate_content',
            'config' => [
                'prompt' => 'Write a meta description using keywords: {{keywords}} for post: {{post_title}}',
                'temperature' => 0.5
            ],
            'output_key' => 'meta_description'
        ],
        [
            'type' => 'update_post',
            'config' => [
                'post_id' => '{{post_id}}',
                'meta' => [
                    '_ai_meta_description' => '{{meta_description}}',
                    '_ai_keywords' => '{{keywords}}'
                ]
            ]
        ],
        [
            'type' => 'slack_notification',
            'config' => [
                'webhook_url' => 'https://hooks.slack.com/services/XXX',
                'message' => '✨ New post enhanced with AI: {{post_title}}'
            ]
        ]
    ],
    'delay' => 60 // Wait 60 seconds before processing
];
Advertisement
[Responsive Leaderboard]

🧠 Machine Learning Model Integration

Integrate custom ML models using PHP-ML and TensorFlow PHP for on-server predictions.

PHP-ML Classification Example

<?php
namespace AIWordPress\ML;

use Phpml\Classification\KNearestNeighbors;
use Phpml\FeatureExtraction\TfIdfTransformer;
use Phpml\Tokenization\WhitespaceTokenizer;
use Phpml\FeatureExtraction\TokenCountVectorizer;

class ContentClassifier {
    private $classifier;
    private $vectorizer;
    private $transformer;
    private $trained = false;
    
    public function __construct() {
        $this->classifier = new KNearestNeighbors();
        $this->vectorizer = new TokenCountVectorizer(new WhitespaceTokenizer());
        $this->transformer = new TfIdfTransformer();
    }
    
    public function train(array $samples, array $labels): void {
        // Vectorize the samples
        $this->vectorizer->fit($samples);
        $this->vectorizer->transform($samples);
        
        // Apply TF-IDF transformation
        $this->transformer->fit($samples);
        $this->transformer->transform($samples);
        
        // Train classifier
        $this->classifier->train($samples, $labels);
        $this->trained = true;
        
        // Save model to options
        $this->saveModel();
    }
    
    public function predict(string $text): array {
        if (!$this->trained) {
            $this->loadModel();
        }
        
        $samples = [$text];
        $this->vectorizer->transform($samples);
        $this->transformer->transform($samples);
        
        $prediction = $this->classifier->predict($samples[0]);
        
        // Get probability
        $probability = $this->getPredictionProbability($text, $prediction);
        
        return [
            'category' => $prediction,
            'confidence' => $probability,
            'text' => $text
        ];
    }
    
    private function getPredictionProbability($text, $prediction): float {
        // Simple distance-based probability
        $distances = $this->classifier->getDistance($text);
        $total = array_sum($distances);
        
        return $total > 0 ? $distances[$prediction] / $total : 0;
    }
    
    private function saveModel(): void {
        $data = [
            'classifier' => serialize($this->classifier),
            'vectorizer' => serialize($this->vectorizer),
            'transformer' => serialize($this->transformer)
        ];
        
        update_option('ai_ml_content_classifier', $data);
    }
    
    private function loadModel(): void {
        $data = get_option('ai_ml_content_classifier');
        
        if ($data) {
            $this->classifier = unserialize($data['classifier']);
            $this->vectorizer = unserialize($data['vectorizer']);
            $this->transformer = unserialize($data['transformer']);
            $this->trained = true;
        }
    }
    
    public function autoClassifyPost(int $postId): void {
        $post = get_post($postId);
        
        if (!$post) {
            return;
        }
        
        $prediction = $this->predict($post->post_title . ' ' . $post->post_content);
        
        // Auto-assign category based on prediction
        if ($prediction['confidence'] > 0.6) {
            $categoryId = $this->getCategoryForLabel($prediction['category']);
            wp_set_post_categories($postId, $categoryId, true);
            
            // Log the auto-classification
            update_post_meta($postId, '_ai_auto_classified', [
                'category' => $prediction['category'],
                'confidence' => $prediction['confidence'],
                'timestamp' => current_time('mysql')
            ]);
        }
    }
    
    private function getCategoryForLabel(string $label): int {
        $map = get_option('ai_ml_category_map', []);
        return $map[$label] ?? 0;
    }
}

// Integration with WordPress
add_action('save_post', function($postId, $post, $update) {
    if ($post->post_status === 'publish' && !$update) {
        $classifier = new ContentClassifier();
        $classifier->autoClassifyPost($postId);
    }
}, 10, 3);

TensorFlow PHP Integration

<?php
namespace AIWordPress\ML;

use TensorFlow\Tensor;
use TensorFlow\Session;
use TensorFlow\Graph;

class TensorFlowPredictor {
    private $session;
    private $graph;
    private $modelPath;
    
    public function __construct(string $modelPath) {
        $this->modelPath = $modelPath;
        $this->loadModel();
    }
    
    private function loadModel(): void {
        $this->graph = new Graph();
        
        // Load frozen graph
        $graphDef = file_get_contents($this->modelPath);
        $this->graph->import($graphDef);
        
        // Create session
        $this->session = new Session($this->graph);
    }
    
    public function predictText(array $texts): array {
        // Preprocess text
        $sequences = $this->tokenize($texts);
        $padded = $this->padSequences($sequences);
        
        // Create tensor
        $inputTensor = Tensor::fromArray($padded);
        
        // Run inference
        $output = $this->session->run([
            'input' => $inputTensor
        ], ['output']);
        
        // Post-process results
        return $this->postProcess($output['output']);
    }
    
    public function predictImage(string $imagePath): array {
        // Load and preprocess image
        $image = $this->loadImage($imagePath);
        $preprocessed = $this->preprocessImage($image);
        
        // Run inference
        $output = $this->session->run([
            'input_image' => Tensor::fromArray($preprocessed)
        ], ['predictions']);
        
        return $this->interpretPredictions($output['predictions']);
    }
    
    private function tokenize(array $texts): array {
        // Implement tokenization logic
        $tokenizer = loadTokenizer();
        return $tokenizer->textsToSequences($texts);
    }
    
    private function padSequences(array $sequences, int $maxLen = 100): array {
        $padded = [];
        foreach ($sequences as $seq) {
            if (count($seq) > $maxLen) {
                $padded[] = array_slice($seq, 0, $maxLen);
            } else {
                $padded[] = array_pad($seq, $maxLen, 0);
            }
        }
        return $padded;
    }
    
    private function loadImage(string $path): array {
        // Implement image loading logic
        // Returns normalized pixel values
    }
}

🚀 PHP 8.3 Performance Optimizations for AI

Leverage PHP 8.3's latest features to maximize AI processing speed.

JIT Configuration Comparison

Configuration AI Task Speed Memory Usage Best For
opcache.jit=tracing 🔥 300% faster +150MB Batch processing, training
opcache.jit=function ⚡ 150% faster +50MB Real-time predictions
opcache.jit=off Baseline Normal Debugging

Optimized Async Processing

<?php
namespace AIWordPress\Performance;

use parallel\Runtime;
use parallel\Channel;

class AsyncAIProcessor {
    private array $runtimes = [];
    private Channel $channel;
    
    public function __construct(int $workers = 4) {
        // Create channel for communication
        $this->channel = Channel::make('ai_tasks');
        
        // Spawn worker threads
        for ($i = 0; $i < $workers; $i++) {
            $this->runtimes[] = new Runtime(__DIR__ . '/worker.php');
        }
    }
    
    public function processBatch(array $tasks): array {
        $futures = [];
        $results = [];
        
        // Distribute tasks to workers
        foreach ($tasks as $task) {
            $futures[] = $this->runtimes[array_rand($this->runtimes)]->run(
                function($task) {
                    // Worker code
                    $processor = new AITaskProcessor();
                    return $processor->execute($task);
                },
                [$task]
            );
        }
        
        // Collect results
        foreach ($futures as $future) {
            $results[] = $future->value();
        }
        
        return $results;
    }
    
    public function processStream(callable $generator): Generator {
        while ($task = $generator()) {
            // Non-blocking task processing
            $future = $this->runtimes[array_rand($this->runtimes)]->run(
                function($task) {
                    return $this->processTask($task);
                },
                [$task]
            );
            
            yield $future;
        }
    }
}

// Fiber-based async processing (PHP 8.1+)
class FiberProcessor {
    public function processWithFibers(array $tasks): array {
        $fibers = [];
        $results = [];
        
        foreach ($tasks as $key => $task) {
            $fibers[$key] = new Fiber(function() use ($task) {
                return $this->aiTask($task);
            });
            $fibers[$key]->start();
        }
        
        foreach ($fibers as $key => $fiber) {
            $results[$key] = $fiber->join();
        }
        
        return $results;
    }
}

Caching Strategy with Redis

<?php
class AICacheManager {
    private $redis;
    private $prefix = 'ai_cache:';
    
    public function __construct() {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
        
        // Load Lua script for atomic operations
        $this->loadScripts();
    }
    
    public function getOrCompute(string $key, callable $callback, int $ttl = 3600) {
        // Try cache first
        $cached = $this->redis->get($this->prefix . $key);
        
        if ($cached !== false) {
            return unserialize($cached);
        }
        
        // Compute value
        $value = $callback();
        
        // Store in cache
        $this->redis->setex(
            $this->prefix . $key,
            $ttl,
            serialize($value)
        );
        
        return $value;
    }
    
    public function remember(string $key, $value, int $ttl = 3600): void {
        $this->redis->setex($this->prefix . $key, $ttl, serialize($value));
    }
    
    public function forget(string $key): void {
        $this->redis->del($this->prefix . $key);
    }
    
    public function tags(array $tags): TaggedCache {
        return new TaggedCache($this->redis, $this->prefix, $tags);
    }
}

class TaggedCache {
    private $redis;
    private $prefix;
    private $tags;
    
    public function __construct($redis, $prefix, $tags) {
        $this->redis = $redis;
        $this->prefix = $prefix;
        $this->tags = $tags;
    }
    
    public function put(string $key, $value, int $ttl = 3600): void {
        $cacheKey = $this->prefix . $key;
        
        // Store value
        $this->redis->setex($cacheKey, $ttl, serialize($value));
        
        // Add to tag sets
        foreach ($this->tags as $tag) {
            $tagKey = $this->prefix . 'tag:' . $tag;
            $this->redis->sadd($tagKey, $cacheKey);
            $this->redis->expire($tagKey, $ttl);
        }
    }
    
    public function flush(): void {
        foreach ($this->tags as $tag) {
            $tagKey = $this->prefix . 'tag:' . $tag;
            $keys = $this->redis->smembers($tagKey);
            
            if (!empty($keys)) {
                $this->redis->del(...$keys);
                $this->redis->del($tagKey);
            }
        }
    }
}

🔒 Security Best Practices for AI Integration

API Key Management

  • Store keys in wp-config.php with salts
  • Use WordPress encryption for database storage
  • Rotate keys every 90 days
  • Implement rate limiting per user/IP
  • Use different keys for development/production
// wp-config.php
define('AI_OPENAI_KEY', 'sk-...');
define('AI_ENCRYPTION_KEY', SECURE_AUTH_KEY);
define('AI_RATE_LIMIT', 100); // requests per hour

Input Validation & Sanitization

  • Always use WordPress sanitization functions
  • Validate AI prompts for harmful content
  • Implement content moderation layer
  • Escape output before display
  • Use nonces for all AJAX requests
// Sanitize AI prompts
$prompt = sanitize_textarea_field($_POST['prompt']);
$prompt = wp_kses($prompt, []);
$prompt = $this->moderateContent($prompt);

Rate Limiting Implementation

class RateLimiter {
    public function checkLimit(string $key, int $limit, int $window = 3600): bool {
        $redis = new Redis();
        $current = $redis->incr("rate_limit:{$key}");
        
        if ($current === 1) {
            $redis->expire("rate_limit:{$key}", $window);
        }
        
        return $current <= $limit;
    }
}

Audit Logging

function log_ai_action($action, $data) {
    $log = [
        'user_id' => get_current_user_id(),
        'action' => $action,
        'data' => $data,
        'ip' => $_SERVER['REMOTE_ADDR'],
        'timestamp' => current_time('mysql')
    ];
    
    $wpdb->insert('ai_audit_log', $log);
}

❓ Advanced AI Integration FAQ

What's the cost of running AI in production?

OpenAI GPT-4 costs ~$0.03 per 1K tokens. With caching and optimization, a typical blog post costs $0.10-0.30. Implement response caching to reduce costs by 70%.

How to handle rate limits?

Implement queue system with exponential backoff. Use WordPress cron for batch processing. Store failed requests and retry with delays.

Best hosting for AI WordPress?

Kinsta, WP Engine, and Cloudways with PHP 8.3, Redis, and 512MB+ memory. Dedicated servers recommended for heavy ML workloads.

How to test AI features safely?

Use staging environment with test API keys. Implement feature flags to toggle AI features. Log all AI interactions for debugging.

Advertisement
[Responsive Large Rectangle]

📬 Get Advanced WordPress Tutorials

Weekly AI, performance, and development guides. No spam.

📢 Share this advanced guide with fellow developers