WordPress如何集成AI生成文章API与OpenAI配置及开发指南

获取AI API密钥与权限配置

在开始集成AI生成文章API之前,你首先需要获取相应的API密钥。以OpenAI为例,访问OpenAI官方网站并注册账户,然后导航至API密钥管理页面创建新密钥。


// OpenAI API密钥示例(实际使用时请替换为你自己的密钥)
const openaiApiKey = 'sk-your-api-key-here';

此代码片段展示了如何定义OpenAI API密钥变量。在实际应用中,建议将密钥存储在环境变量或WordPress的安全选项中,而非直接硬编码在文件中。

对于其他AI服务提供商如DeepSeek、豆包或Gemini,获取API密钥的流程类似,通常需要在其开发者平台注册并创建应用。

WordPress环境准备与插件开发基础

创建一个自定义WordPress插件是集成AI生成文章API的最佳方式。首先,在wp-content/plugins目录下创建一个新的文件夹,例如"ai-content-generator",并在其中创建主PHP文件。


<?php
/
  Plugin Name: AI Content Generator
  Description: Integrates AI APIs to generate content for WordPress
  Version: 1.0
  Author: Your Name
 /

// 防止直接访问此文件
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('AI_CONTENT_GENERATOR_VERSION', '1.0');
define('AI_CONTENT_GENERATOR_PATH', plugin_dir_path(__FILE__));
define('AI_CONTENT_GENERATOR_URL', plugin_dir_url(__FILE__));

以上代码创建了一个基本的WordPress插件结构,包含了必要的插件头信息和安全检查。定义的常量将在整个插件中使用,便于引用文件路径和URL。

OpenAI API集成实现

接下来,我们将实现与OpenAI API的集成。创建一个类来处理所有API请求和响应。


class AI_Content_Generator_OpenAI {
    private $api_key;
    private $api_endpoint = 'https://api.openai.com/v1/chat/completions';
    
    public function __construct($api_key) {
        $this->api_key = $api_key;
    }
    
    public function generate_content($prompt, $model = 'gpt-3.5-turbo', $max_tokens = 1000) {
        $request_body = array(
            'model' => $model,
            'messages' => array(
                array(
                    'role' => 'user',
                    'content' => $prompt
                )
            ),
            'max_tokens' => $max_tokens,
            'temperature' => 0.7
        );
        
        $response = wp_remote_post($this->api_endpoint, array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $this->api_key
            ),
            'body' => json_encode($request_body),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return array('error' => $response->get_error_message());
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['error'])) {
            return array('error' => $body['error']['message']);
        }
        
        return array(
            'content' => $body['choices'][0]['message']['content'],
            'usage' => $body['usage']
        );
    }
}

这段代码实现了一个完整的OpenAI API客户端类。构造函数接收API密钥,generate_content方法处理API请求并返回生成的内容。注意我们使用了WordPress的wp_remote_post函数来发送HTTP请求,这是WordPress推荐的方式,可以确保与各种服务器环境的兼容性。

WordPress后台设置页面创建

为了方便用户配置API密钥和其他选项,我们需要在WordPress后台创建一个设置页面。


class AI_Content_Generator_Settings {
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'settings_init'));
    }
    
    public function add_admin_menu() {
        add_options_page(
            'AI Content Generator', 
            'AI Content Generator', 
            'manage_options', 
            'ai_content_generator', 
            array($this, 'settings_page_html')
        );
    }
    
    public function settings_init() {
        register_setting('ai_content_generator', 'ai_content_generator_settings');
        
        add_settings_section(
            'ai_content_generator_section',
            __('API Configuration', 'ai-content-generator'),
            array($this, 'settings_section_callback'),
            'ai_content_generator'
        );
        
        add_settings_field(
            'openai_api_key',
            __('OpenAI API Key', 'ai-content-generator'),
            array($this, 'api_key_field_render'),
            'ai_content_generator',
            'ai_content_generator_section'
        );
        
        // 可以添加更多API提供商的设置字段
    }
    
    public function api_key_field_render() {
        $options = get_option('ai_content_generator_settings');
        $api_key = isset($options['openai_api_key']) ? $options['openai_api_key'] : '';
        ?>
        <input type='password' name='ai_content_generator_settings[openai_api_key]' value='' class='regular-text'>
        
        

<?php } } // 初始化设置类 new AI_Content_Generator_Settings();

这段代码创建了一个完整的WordPress设置页面,允许用户安全地存储他们的OpenAI API密钥。我们使用了WordPress设置API来处理表单渲染和数据保存,确保了安全性和一致性。

内容生成功能实现

现在,我们将实现实际的内容生成功能,包括在文章编辑界面添加一个元框,允许用户输入提示并生成内容。


class AI_Content_Generator_Meta_Box {
    public function __construct() {
        add_action('add_meta_boxes', array($this, 'add_meta_box'));
        add_action('save_post', array($this, 'save_meta_box_data'));
        add_action('wp_ajax_generate_ai_content', array($this, 'ajax_generate_content'));
    }
    
    public function add_meta_box() {
        add_meta_box(
            'ai_content_generator',
            __('AI Content Generator', 'ai-content-generator'),
            array($this, 'render_meta_box'),
            'post',
            'normal',
            'high'
        );
    }
    
    public function render_meta_box($post) {
        wp_nonce_field('ai_content_generator_nonce', 'ai_content_generator_nonce_field');
        ?>
        

WordPress如何集成AI生成文章API与OpenAI配置及开发指南

GPT-3.5 Turbo GPT-4

jQuery(document).ready(function($) { $('generate_ai_content').on('click', function() { var prompt = $('ai_content_prompt').val(); var model = $('ai_content_model').val(); var nonce = $('ai_content_generator_nonce_field').val(); var postId = $('post_ID').val(); var $button = $(this); var $spinner = $button.next('.spinner'); if (!prompt) { alert(''); return; } $button.prop('disabled', true); $spinner.addClass('is-active'); $.ajax({ url: ajaxurl, type: 'POST', data: { action: 'generate_ai_content', prompt: prompt, model: model, post_id: postId, nonce: nonce }, success: function(response) { if (response.success) { $('ai_content_result').(response.data.content); $('ai_generated_content').show(); } else { alert(response.data.error || ''); } }, error: function() { alert(''); }, complete: function() { $button.prop('disabled', false); $spinner.removeClass('is-active'); } }); }); $('insert_ai_content').on('click', function() { var content = $('ai_content_result').(); if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) { tinyMCE.activeEditor.setContent(content); } else { $('content').val(content); } }); }); __('You do not have permission to generate content.', 'ai-content-generator'))); } $prompt = sanitize_textarea_field($_POST['prompt']); $model = sanitize_text_field($_POST['model']); if (empty($prompt)) { wp_send_json_error(array('error' => __('Please provide a prompt.', 'ai-content-generator'))); } $options = get_option('ai_content_generator_settings'); $api_key = isset($options['openai_api_key']) ? $options['openai_api_key'] : ''; if (empty($api_key)) { wp_send_json_error(array('error' => __('API key is not configured.', 'ai-content-generator'))); } $openai = new AI_Content_Generator_OpenAI($api_key); $result = $openai->generate_content($prompt, $model); if (isset($result['error'])) { wp_send_json_error(array('error' => $result['error'])); } wp_send_json_success(array( 'content' => wpautop($result['content']), 'usage' => $result['usage'] )); } public function save_meta_box_data($post_id) { if (!isset($_POST['ai_content_generator_nonce_field'])) { return; } if (!wp_verify_nonce($_POST['ai_content_generator_nonce_field'], 'ai_content_generator_nonce')) { return; } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } if (!current_user_can('edit_post', $post_id)) { return; } } } // 初始化元框类 new AI_Content_Generator_Meta_Box();

这段代码实现了一个完整的WordPress文章编辑界面中的AI内容生成功能。它添加了一个元框,允许用户输入提示、选择AI模型,然后通过AJAX请求生成内容。生成的内容可以直接插入到WordPress编辑器中。

多AI模型支持扩展

为了支持多种AI模型(如DeepSeek、豆包、Gemini等),我们需要扩展我们的实现。首先,创建一个基础接口类,然后为每个AI提供商实现具体的类。


interface AI_Content_Generator_Interface {
    public function generate_content($prompt, $options = array());
}

class AI_Content_Generator_DeepSeek implements AI_Content_Generator_Interface {
    private $api_key;
    private $api_endpoint = 'https://api.deepseek.com/v1/chat/completions';
    
    public function __construct($api_key) {
        $this->api_key = $api_key;
    }
    
    public function generate_content($prompt, $options = array()) {
        $model = isset($options['model']) ? $options['model'] : 'deepseek-chat';
        $max_tokens = isset($options['max_tokens']) ? $options['max_tokens'] : 1000;
        
        $request_body = array(
            'model' => $model,
            'messages' => array(
                array(
                    'role' => 'user',
                    'content' => $prompt
                )
            ),
            'max_tokens' => $max_tokens,
            'temperature' => 0.7
        );
        
        $response = wp_remote_post($this->api_endpoint, array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $this->api_key
            ),
            'body' => json_encode($request_body),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return array('error' => $response->get_error_message());
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['error'])) {
            return array('error' => $body['error']['message']);
        }
        
        return array(
            'content' => $body['choices'][0]['message']['content'],
            'usage' => $body['usage']
        );
    }
}

class AI_Content_Generator_Doubao implements AI_Content_Generator_Interface {
    private $api_key;
    private $api_endpoint = 'https://api.doubao.com/v1/chat/completions';
    
    public function __construct($api_key) {
        $this->api_key = $api_key;
    }
    
    public function generate_content($prompt, $options = array()) {
        // 实现与DeepSeek类似,但根据豆包API的具体要求调整
        // ...
    }
}

class AI_Content_Generator_Manager {
    private $providers = array();
    
    public function register_provider($name, AI_Content_Generator_Interface $provider) {
        $this->providers[$name] = $provider;
    }
    
    public function generate_content($provider_name, $prompt, $options = array()) {
        if (!isset($this->providers[$provider_name])) {
            return array('error' => __('Provider not found.', 'ai-content-generator'));
        }
        
        return $this->providers[$provider_name]->generate_content($prompt, $options);
    }
    
    public function get_providers() {
        return array_keys($this->providers);
    }
}

这段代码实现了一个灵活的多AI模型支持系统。我们首先定义了一个接口,然后为每个AI提供商实现具体的类。最后,我们创建了一个管理器类,用于注册和使用不同的AI提供商。这种设计使得添加新的AI提供商变得非常简单,只需实现接口并注册到管理器中即可。

API调用优化与错误处理

为了确保API调用的稳定性和效率,我们需要实现适当的缓存机制和错误处理策略。


class AI_Content_Generator_Cache {
    private $cache_group = 'ai_content_generator';
    private $cache_expiration = 3600; // 1小时
    
    public function get($key) {
        return wp_cache_get($key, $this->cache_group);
    }
    
    public function set($key, $data, $expiration = null) {
        if ($expiration === null) {
            $expiration = $this->cache_expiration;
        }
        
        return wp_cache_set($key, $data, $expiration, $this->cache_group);
    }
    
    public function delete($key) {
        return wp_cache_delete($key, $this->cache_group);
    }
    
    public function generate_cache_key($provider, $prompt, $options) {
        $data = array(
            'provider' => $provider,
            'prompt' => $prompt,
            'options' => $options
        );
        
        return md5(serialize($data));
    }
}

class AI_Content_Generator_Error_Handler {
    public function handle_api_error($error, $provider, $prompt, $options) {
        $error_code = isset($error['code']) ? $error['code'] : 'unknown_error';
        $error_message = isset($error['message']) ? $error['message'] : __('An unknown error occurred.', 'ai-content-generator');
        
        // 记录错误
        error_log(sprintf(
            'AI Content Generator Error: Provider: %s, Error: %s, Prompt: %s',
            $provider,
            $error_message,
            substr($prompt, 0, 100) . '...'
        ));
        
        // 根据错误类型采取不同的处理策略
        switch ($error_code) {
            case 'rate_limit_exceeded':
                // 返回特定的错误消息,建议用户稍后重试
                return array(
                    'error' => __('API rate limit exceeded. Please try again later.', 'ai-content-generator'),
                    'retry_after' => isset($error['retry_after']) ? $error['retry_after'] : 60
                );
                
            case 'invalid_api_key':
                // 返回特定的错误消息,提示用户检查API密钥
                return array(
                    'error' => __('Invalid API key. Please check your API key configuration.', 'ai-content-generator')
                );
                
            case 'insufficient_quota':
                // 返回特定的错误消息,提示用户配额不足
                return array(
                    'error' => __('Insufficient quota. Please check your API plan.', 'ai-content-generator')
                );
                
            default:
                // 返回通用错误消息
                return array(
                    'error' => sprintf(__('API error: %s', 'ai-content-generator'), $error_message)
                );
        }
    }
}

// 修改AI_Content_Generator_Manager类以支持缓存和错误处理
class AI_Content_Generator_Manager_Enhanced {
    private $providers = array();
    private $cache;
    private $error_handler;
    private $enable_cache = true;
    
    public function __construct() {
        $this->cache = new AI_Content_Generator_Cache();
        $this->error_handler = new AI_Content_Generator_Error_Handler();
    }
    
    public function register_provider($name, AI_Content_Generator_Interface $provider) {
        $this->providers[$name] = $provider;
    }
    
    public function generate_content($provider_name, $prompt, $options = array()) {
        if (!isset($this->providers[$provider_name])) {
            return array('error' => __('Provider not found.', 'ai-content-generator'));
        }
        
        // 检查缓存
        if ($this->enable_cache) {
            $cache_key = $this->cache->generate_cache_key($provider_name, $prompt, $options);
            $cached_result = $this->cache->get($cache_key);
            
            if ($cached_result !== false) {
                return $cached_result;
            }
        }
        
        // 调用API生成内容
        $result = $this->providers[$provider_name]->generate_content($prompt, $options);
        
        // 处理错误
        if (isset($result['error'])) {
            return $this->error_handler->handle_api_error($result['error'], $provider_name, $prompt, $options);
        }
        
        // 缓存结果
        if ($this->enable_cache && isset($result['content'])) {
            $cache_key = $this->cache->generate_cache_key($provider_name, $prompt, $options);
            $this->cache->set($cache_key, $result);
        }
        
        return $result;
    }
    
    public function set_cache_enabled($enabled) {
        $this->enable_cache = (bool) $enabled;
    }
    
    public function get_providers() {
        return array_keys($this->providers);
    }
}

这段代码实现了两个重要的辅助类:缓存管理器和错误处理器。缓存管理器使用WordPress的对象缓存来存储API响应,减少重复请求。错误处理器则根据不同类型的API错误提供适当的处理策略和用户友好的错误消息。我们还增强了管理器类,使其能够利用这些辅助功能。

实际应用场景与高级功能

现在,让我们实现一些实际应用场景和高级功能,如批量生成文章、自动发布和内容优化建议。


class AI_Content_Generator_Batch {
    private $manager;
    
    public function __construct($manager) {
        $this->manager = $manager;
        add_action('wp_ajax_generate_batch_content', array($this, 'ajax_generate_batch_content'));
    }
    
    public function render_batch_interface() {
        if (!current_user_can('publish_posts')) {
            return;
        }
        ?>
        

manager->get_providers(); foreach ($providers as $provider) { echo '' . esc_html($provider) . ''; } ?>
<textarea name="template" id="batch-template" rows="5" class="large-text" placeholder="">

__('— Select Category —', 'ai-content-generator'), 'name' => 'post_category', 'id' => 'batch-post-category', 'orderby' => 'name', 'hierarchical' => true )); ?>

0%

jQuery(document).ready(function($) { $('generate-batch-content').on('click', function() { var provider = $('batch-provider').val(); var template = $('batch-template').val(); var keywords = $('batch-keywords').val().split('n').filter(k => k.trim() !== ''); var postStatus = $('batch-post-status').val(); var postCategory = $('batch-post-category').val(); var nonce = $('ai_content_generator_nonce_field').val(); if (!template) { alert(''); return; } if (keywords.length === 0) { alert(''); return; } var $button = $(this); var $spinner = $button.next('.spinner'); var $progressContainer = $('batch-progress'); var $progressBar = $progressContainer.find('.progress'); var $progressText = $progressContainer.find('.progress-text'); var $results = $progressContainer.find('.batch-results'); $button.prop('disabled', true); $spinner.addClass('is-active'); $progressContainer.show(); $results.empty(); var total = keywords.length; var completed = 0; function processNextKeyword() { if (completed >= total) { $button.prop('disabled', false); $spinner.removeClass('is-active'); alert(''); return; } var keyword = keywords[completed].trim(); var prompt = template.replace(/{keyword}/g, keyword); $.ajax({ url: ajaxurl, type: 'POST', data: { action: 'generate_batch_content', provider: provider, prompt: prompt, keyword: keyword, post_status: postStatus, post_category: postCategory, nonce: nonce }, success: function(response) { completed++; var progress = Math.round((completed / total) 100); $progressBar.css('width', progress + '%'); $progressText.text(progress + '%'); if (response.success) { $results.append('
' + keyword + ' -
'); } else { $results.append('
' + keyword + ' - ' + (response.data.error || '') + '
'); } processNextKeyword(); }, error: function() { completed++; var progress = Math.round((completed / total) 100); $progressBar.css('width', progress + '%'); $progressText.text(progress + '%'); $results.append('
' + keyword + ' -
'); processNextKeyword(); } }); } processNextKeyword(); }); }); .progress-bar { width: 100%; height: 20px; background-color: f0f0f1; border-radius: 3px; margin: 10px 0; } .progress { height: 100%; background-color: 2271b1; border-radius: 3px; transition: width 0.3s; } .batch-item { padding: 8px; margin: 5px 0; border-radius: 3px; } .batch-item.success { background-color: d4edda; color: 155724; } .batch-item.error { background-color: f8d7da; color: 721c24; } __('You do not have permission to publish posts.', 'ai-content-generator'))); } $provider = sanitize_text_field($_POST['provider']); $prompt = sanitize_textarea_field($_POST['prompt']); $keyword = sanitize_text_field($_POST['keyword']); $post_status = sanitize_text_field($_POST['post_status']); $post_category = intval($_POST['post_category']); if (empty($prompt)) { wp_send_json_error(array('error' => __('Prompt is empty.', 'ai-content-generator'))); } // 生成内容 $result = $this->manager->generate_content($provider, $prompt); if (isset($result['error'])) { wp_send_json_error(array('error' => $result['error'])); } // 创建文章 $post_data = array( 'post_title' => $keyword, 'post_content' => $result['content'], 'post_status' => $post_status, 'post_category' => array($post_category), 'post_author' => get_current_user_id() ); $post_id = wp_insert_post($post_data); if (is_wp_error($post_id)) { wp_send_json_error(array('error' => $post_id->get_error_message())); } wp_send_json_success(array( 'message' => __('Post created successfully.', 'ai-content-generator'), 'post_id' => $post_id, 'edit_link' => get_edit_post_link($post_id) )); } } // 添加批量生成页面 function ai_content_generator_batch_menu() { add_submenu_page( 'options-general.php', __('Batch Content Generation', 'ai-content-generator'), __('Batch Generation', 'ai-content-generator'), 'publish_posts', 'ai_content_generator_batch', 'ai_content_generator_batch_page' ); } add_action('admin_menu', 'ai_content_generator_batch_menu'); function ai_content_generator_batch_page() { $manager = new AI_Content_Generator_Manager_Enhanced(); // 注册AI提供商 $options = get_option('ai_content_generator_settings'); if (!empty($options['openai_api_key'])) { $manager->register_provider('OpenAI', new AI_Content_Generator_OpenAI($options['openai_api_key'])); } if (!empty($options['deepseek_api_key'])) { $manager->register_provider('DeepSeek', new AI_Content_Generator_DeepSeek($options['deepseek_api_key'])); } $batch_generator = new AI_Content_Generator_Batch($manager); $batch_generator->render_batch_interface(); }

这段代码实现了一个批量内容生成功能,允许用户使用模板和关键词列表批量生成文章。用户可以定义一个内容模板,使用{keyword}作为占位符,然后提供一个关键词列表。系统将为每个关键词生成一篇文章,并可以选择直接发布或保存为草稿。界面还包括进度条和结果反馈,使用户能够清楚地了解生成过程。

AI内容优化建议功能

最后,让我们实现一个AI内容优化建议功能,帮助用户改进他们已经编写的内容。


class AI_Content_Generator_Optimizer {
    private $manager;
    
    public function __construct($manager) {
        $this->manager = $manager;
        add_action('add_meta_boxes', array($this, 'add_optimizer_meta_box'));
        add_action('wp_ajax_optimize_content', array($this, 'ajax_optimize_content'));
    }
    
    public function add_optimizer_meta_box() {
        add_meta_box(
            'ai_content_optimizer',
            __('AI Content Optimizer', 'ai-content-generator'),
            array($this, 'render_optimizer_meta_box'),
            'post',
            'side',
            'default'
        );
    }
    
    public function render_optimizer_meta_box($post) {
        wp_nonce_field('ai_content_optimizer_nonce', 'ai_content_optimizer_nonce_field');
        ?>
        

jQuery(document).ready(function($) { var currentOperation = ''; function showLoading() { $('optimizer-results').hide(); $('.ai-content-optimizer button').prop('disabled', true); } function hideLoading() { $('.ai-content-optimizer button').prop('disabled', false); } function optimizeContent(operation) { currentOperation = operation; showLoading(); var content = ''; if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) { content = tinyMCE.activeEditor.getContent(); } else { content = $('content').val(); } if (!content) { alert(''); hideLoading(); return; } var title = $('title').val(); var nonce = $('ai_content_optimizer_nonce_field').val(); var postId = $('post_ID').val(); $.ajax({ url: ajaxurl, type: 'POST', data: { action: 'optimize_content', operation: operation, content: content, title: title, post_id: postId, nonce: nonce }, success: function(response) { if (response.success) { $('.optimizer-content').(response.data.content); $('optimizer-results').show(); } else { alert(response.data.error || ''); } }, error: function() { alert(''); }, complete: function() { hideLoading(); } }); } $('analyze_seo').on('click', function() { optimizeContent('seo'); }); $('improve_readability').on('click', function() { optimizeContent('readability'); }); $('expand_content').on('click', function() { optimizeContent('expand'); }); $('generate_meta_description').on('click', function() { optimizeContent('meta_description'); }); $('apply_optimization').on('click', function() { var optimizedContent = $('.optimizer-content').(); if (currentOperation === 'meta_description') { // 如果是生成meta description,则设置到excerpt字段 $('excerpt').val(optimizedContent.replace(/]>/g, '').trim()); } else { // 其他操作则更新内容 if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) { tinyMCE.activeEditor.setContent(optimizedContent); } else { $('content').val(optimizedContent); } } $('optimizer-results').hide(); }); }); __('You do not have permission to edit posts.', 'ai-content-generator'))); } $operation = sanitize_text_field($_POST['operation']); $content = wp_kses_post($_POST['content']); $title = sanitize_text_field($_POST['title']); if (empty($content)) { wp_send_json_error(array('error' => __('Content is empty.', 'ai-content-generator'))); } // 根据操作类型生成不同的提示 switch ($operation) { case 'seo': $prompt = "Analyze the following content for SEO optimization and provide specific suggestions to improve its search engine ranking. Include recommendations for keyword usage, meta tags, headings, and overall structure.nnTitle: {$title}nnContent: {$content}"; break; case 'readability': $prompt = "Improve the readability of the following content. Make it more engaging, easier to understand, and better structured. Break up long paragraphs, use simpler language where appropriate, and improve flow.nnTitle: {$title}nnContent: {$content}"; break; case 'expand': $prompt = "Expand the following content by adding more details, examples, and insights. Make it more comprehensive and valuable to readers while maintaining the original structure and key points.nnTitle: {$title}nnContent: {$content}"; break; case 'meta_description': $prompt = "Generate a compelling meta description (under 160 characters) for the following content that will improve click-through rates from search results.nnTitle: {$title}nnContent: {$content}"; break; default: wp_send_json_error(array('error' => __('Invalid operation.', 'ai-content-generator'))); } // 获取默认提供商 $providers = $this->manager->get_providers(); if (empty($providers)) { wp_send_json_error(array('error' => __('No AI providers configured.', 'ai-content-generator'))); } $default_provider = $providers[0]; // 生成优化建议 $result = $this->manager->generate_content($default_provider, $prompt); if (isset($result['error'])) { wp_send_json_error(array('error' => $result['error'])); } wp_send_json_success(array( 'content' => wpautop($result['content']) )); } } // 初始化优化器 function ai_content_generator_init_optimizer() { $manager = new AI_Content_Generator_Manager_Enhanced(); // 注册AI提供商 $options = get_option('ai_content_generator_settings'); if (!empty($options['openai_api_key'])) { $manager->register_provider('OpenAI', new AI_Content_Generator_OpenAI($options['openai_api_key'])); } if (!empty($options['deepseek_api_key'])) { $manager->register_provider('DeepSeek', new AI_Content_Generator_DeepSeek($options['deepseek_api_key'])); } new AI_Content_Generator_Optimizer($manager); } add_action('admin_init', 'ai_content_generator_init_optimizer');

这段代码实现了一个AI内容优化建议功能,它添加了一个元框到文章编辑界面,提供四种不同的优化选项:SEO分析、可读性改进、内容扩展和生成meta描述。用户可以选择其中一种操作,系统将使用AI分析当前内容并提供优化建议。用户可以选择应用这些建议来改进他们的内容。