WordPress如何接入Gemini API实现内容生成与插件支持

Gemini API准备工作

在WordPress网站中接入Gemini API前,你需要完成一系列准备工作。首先,访问Google AI平台并创建一个项目。登录你的Google Cloud账号后,导航至AI Platform部分,选择"模型"下的Gemini选项。

WordPress如何接入Gemini API实现内容生成与插件支持

创建新项目后,你需要启用Gemini API。在项目仪表板中,找到"API和服务"部分,点击"库",然后搜索"Gemini API"并启用它。这个过程可能需要几分钟时间来完成初始化。

获取API密钥

启用Gemini API后,下一步是获取API密钥。导航至"凭据"页面,点击"创建凭据",选择"API密钥"。系统将生成一个唯一的密钥,这个密钥是你WordPress网站与Gemini服务通信的关键。

重要提示:请妥善保管你的API密钥,不要将其直接暴露在网站前端代码中。API密钥泄露可能导致未授权使用,产生额外费用。建议将密钥存储在WordPress的环境变量或使用安全插件管理。

WordPress环境配置

确保你的WordPress环境满足接入Gemini API的基本要求。最低PHP版本应为7.4或更高,同时需要启用cURL扩展以支持HTTP请求。大多数现代WordPress托管环境已默认满足这些要求,但进行配置前仍需确认。

服务器兼容性检查

通过以下PHP代码检查你的服务器环境是否兼容Gemini API集成:


<?php
// 检查PHP版本
if (version_compare(PHP_VERSION, '7.4.0', '<')) {
    echo '错误:PHP版本过低,需要7.4或更高版本。当前版本:' . PHP_VERSION;
} else {
    echo 'PHP版本检查通过:' . PHP_VERSION;
}

// 检查cURL扩展
if (!extension_loaded('curl')) {
    echo '错误:cURL扩展未启用。';
} else {
    echo 'cURL扩展已启用。';
}

// 检查JSON扩展
if (!extension_loaded('json')) {
    echo '错误:JSON扩展未启用。';
} else {
    echo 'JSON扩展已启用。';
}
?>

将此代码保存为PHP文件,通过FTP上传到你的WordPress根目录并访问,或使用WordPress的代码片段插件执行。如果所有检查都通过,你的环境已准备好接入Gemini API。

通过插件接入Gemini API

WordPress插件生态系统中已有多个支持Gemini AI的插件,这些插件简化了API集成过程。以下是几个主流选项及其配置方法。

AI Content Generator插件

AI Content Generator是一个支持Gemini API的WordPress插件,它允许你直接在文章编辑器中使用AI生成内容。安装步骤如下:

  1. 在WordPress后台导航至"插件" > "安装插件"
  2. 搜索"AI Content Generator"
  3. 点击"现在安装"并激活插件
  4. 导航至"设置" > "AI Content Generator"
  5. 在"API密钥"字段中输入你的Gemini API密钥
  6. 选择"Gemini"作为默认AI模型
  7. 保存设置

配置完成后,你可以在文章编辑器中看到一个新的"AI生成内容"按钮。点击此按钮将打开一个界面,允许你输入提示词并选择生成的内容类型。

自定义代码集成方法

对于需要更多控制权的开发者,直接通过代码集成Gemini API是更好的选择。以下是一个基本的WordPress函数,用于向Gemini API发送请求并获取响应:


function send_to_gemini_api($prompt, $api_key) {
    $api_url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=' . $api_key;
    
    $request_body = array(
        'contents' => array(
            array(
                'parts' => array(
                    array(
                        'text' => $prompt
                    )
                )
            )
        )
    );
    
    $args = array(
        'body' => json_encode($request_body),
        'headers' => array(
            'Content-Type' => 'application/json',
        ),
        'timeout' => 60,
    );
    
    $response = wp_remote_post($api_url, $args);
    
    if (is_wp_error($response)) {
        return '错误:' . $response->get_error_message();
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
        return $data['candidates'][0]['content']['parts'][0]['text'];
    } else {
        return '错误:无法从API响应中提取内容。';
    }
}

将此代码添加到你的主题的functions.php文件或自定义插件中。使用时,只需调用此函数并传入提示词和API密钥:


$api_key = '你的Gemini_API密钥';
$prompt = '写一段关于人工智能在WordPress中应用的介绍';
$generated_content = send_to_gemini_api($prompt, $api_key);
echo $generated_content;

内容生成工作流集成

将Gemini API集成到WordPress内容生成工作流中,可以显著提高内容创作效率。以下是几种实用的集成方法。

自动文章生成

创建一个自定义文章类型,专门用于管理AI生成的内容。首先,注册自定义文章类型:


function register_ai_content_post_type() {
    $args = array(
        'public' => true,
        'label'  => 'AI生成内容',
        'supports' => array('title', 'editor', 'thumbnail'),
        'menu_icon' => 'dashicons-edit-page',
    );
    register_post_type('ai_content', $args);
}
add_action('init', 'register_ai_content_post_type');

然后,添加一个元框,用于输入AI提示词和触发内容生成:


function add_ai_prompt_meta_box() {
    add_meta_box(
        'ai_prompt_meta_box',
        'AI提示词',
        'ai_prompt_meta_box_callback',
        'ai_content',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_ai_prompt_meta_box');

function ai_prompt_meta_box_callback($post) {
    wp_nonce_field('ai_prompt_meta_box', 'ai_prompt_nonce');
    $value = get_post_meta($post->ID, '_ai_prompt', true);
    echo '<textarea id="ai_prompt" name="ai_prompt" style="width:100%;height:150px;">' . esc_textarea($value) . '</textarea>';
    echo '<button type="button" id="generate_content" class="button button-primary">生成内容</button>';
    echo '<div id="ai_response" style="margin-top:10px;padding:10px;background:f1f1f1;border-left:4px solid 00a0d2;display:none;"></div>';
}

function save_ai_prompt_meta_box_data($post_id) {
    if (!isset($_POST['ai_prompt_nonce'])) {
        return;
    }
    if (!wp_verify_nonce($_POST['ai_prompt_nonce'], 'ai_prompt_meta_box')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    if (isset($_POST['ai_prompt'])) {
        update_post_meta($post_id, '_ai_prompt', sanitize_text_field($_POST['ai_prompt']));
    }
}
add_action('save_post', 'save_ai_prompt_meta_box_data');

最后,添加JavaScript代码处理API请求和内容插入:


function add_ai_generator_script() {
    global $post;
    if ($post->post_type == 'ai_content') {
        wp_enqueue_script('ai-generator', get_template_directory_uri() . '/js/ai-generator.js', array('jquery'), '1.0', true);
        wp_localize_script('ai-generator', 'ai_vars', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'api_key' => '你的Gemini_API密钥',
            'nonce' => wp_create_nonce('ai_generator_nonce')
        ));
    }
}
add_action('admin_enqueue_scripts', 'add_ai_generator_script');

// 创建ai-generator.js文件并添加以下代码
/
jQuery(document).ready(function($) {
    $('generate_content').click(function() {
        var prompt = $('ai_prompt').val();
        var responseDiv = $('ai_response');
        
        if (!prompt) {
            responseDiv.text('请输入提示词').show();
            return;
        }
        
        responseDiv.text('生成中,请稍候...').show();
        
        $.ajax({
            url: ai_vars.ajax_url,
            type: 'POST',
            data: {
                action: 'generate_ai_content',
                prompt: prompt,
                nonce: ai_vars.nonce
            },
            success: function(response) {
                if (response.success) {
                    responseDiv.text(response.data).show();
                    if (confirm('是否将生成的内容插入到编辑器中?')) {
                        if (window.tinymce) {
                            window.tinymce.activeEditor.setContent(response.data);
                        } else {
                            $('content').val(response.data);
                        }
                    }
                } else {
                    responseDiv.text('错误:' + response.data).show();
                }
            },
            error: function() {
                responseDiv.text('请求失败,请重试').show();
            }
        });
    });
});
/

function handle_generate_ai_content() {
    check_ajax_referer('ai_generator_nonce', 'nonce');
    
    if (!current_user_can('edit_posts')) {
        wp_send_json_error('权限不足');
    }
    
    $prompt = sanitize_text_field($_POST['prompt']);
    if (empty($prompt)) {
        wp_send_json_error('提示词不能为空');
    }
    
    $api_key = '你的Gemini_API密钥'; // 实际应用中应从安全位置获取
    $generated_content = send_to_gemini_api($prompt, $api_key);
    
    if (strpos($generated_content, '错误:') === 0) {
        wp_send_json_error($generated_content);
    } else {
        wp_send_json_success($generated_content);
    }
}
add_action('wp_ajax_generate_ai_content', 'handle_generate_ai_content');

批量内容生成与发布

对于需要批量生成内容的场景,可以创建一个WordPress管理页面,用于管理批量内容生成任务:


function add_bulk_ai_generator_menu() {
    add_menu_page(
        '批量AI内容生成器',
        'AI批量生成',
        'manage_options',
        'bulk-ai-generator',
        'bulk_ai_generator_page',
        'dashicons-edit-page',
        30
    );
}
add_action('admin_menu', 'add_bulk_ai_generator_menu');

function bulk_ai_generator_page() {
    if (!current_user_can('manage_options')) {
        return;
    }
    ?>
    <div class="wrap">
        <h1>批量AI内容生成器</h1>
        <form method="post" action="">
            <table class="form-table">
                <tr>
                    <th scope="row">提示词模板</th>
                    <td>
                        <textarea name="prompt_template" rows="5" cols="50" required>写一篇关于{关键词}的详细文章,包括介绍、优点和缺点</textarea>
                        <p class="description">使用{关键词}作为变量占位符</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">关键词列表</th>
                    <td>
                        <textarea name="keywords" rows="10" cols="50" required>人工智能
机器学习
深度学习
自然语言处理</textarea>
                        <p class="description">每行一个关键词</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">发布设置</th>
                    <td>
                        <label>
                            <input type="checkbox" name="publish_immediately" value="1"> 立即发布
                        </label>
                        <br>
                        <label>
                            <input type="checkbox" name="add_to_category" value="1"> 添加到分类
                        </label>
                        <select name="category_id">
                            <?php
                            $categories = get_categories();
                            foreach ($categories as $category) {
                                echo '<option value="' . $category->term_id . '">' . $category->name . '</option>';
                            }
                            ?>
                        </select>
                    </td>
                </tr>
            </table>
            <?php submit_button('开始批量生成'); ?>
        </form>
    </div>
    <?php
}

function handle_bulk_ai_generation() {
    if (!isset($_POST['submit']) || !current_user_can('manage_options')) {
        return;
    }
    
    $prompt_template = sanitize_textarea_field($_POST['prompt_template']);
    $keywords = sanitize_textarea_field($_POST['keywords']);
    $publish_immediately = isset($_POST['publish_immediately']) ? true : false;
    $add_to_category = isset($_POST['add_to_category']) ? intval($_POST['category_id']) : 0;
    
    if (empty($prompt_template) || empty($keywords)) {
        echo '<div class="notice notice-error"><p>请填写所有必填字段</p></div>';
        return;
    }
    
    $keyword_list = explode("n", $keywords);
    $api_key = '你的Gemini_API密钥'; // 实际应用中应从安全位置获取
    
    echo '<div class="notice notice-info"><p>开始批量生成内容...</p></div>';
    
    foreach ($keyword_list as $keyword) {
        $keyword = trim($keyword);
        if (empty($keyword)) {
            continue;
        }
        
        $prompt = str_replace('{关键词}', $keyword, $prompt_template);
        $generated_content = send_to_gemini_api($prompt, $api_key);
        
        if (strpos($generated_content, '错误:') === 0) {
            echo '<div class="notice notice-error"><p>生成"' . $keyword . '"内容时出错:' . $generated_content . '</p></div>';
            continue;
        }
        
        $post_data = array(
            'post_title' => wp_strip_all_tags($keyword),
            'post_content' => $generated_content,
            'post_status' => $publish_immediately ? 'publish' : 'draft',
            'post_author' => get_current_user_id(),
            'post_type' => 'post',
        );
        
        if ($add_to_category > 0) {
            $post_data['post_category'] = array($add_to_category);
        }
        
        $post_id = wp_insert_post($post_data);
        
        if (is_wp_error($post_id)) {
            echo '<div class="notice notice-error"><p>创建"' . $keyword . '"文章时出错:' . $post_id->get_error_message() . '</p></div>';
        } else {
            echo '<div class="notice notice-success"><p>成功创建"' . $keyword . '"文章(ID:' . $post_id . ')</p></div>';
        }
        
        // 避免API速率限制
        sleep(2);
    }
}
add_action('admin_init', 'handle_bulk_ai_generation');

API调用量优化与成本控制

在使用Gemini API时,合理控制API调用量和成本至关重要。以下是一些实用的优化策略。

请求缓存机制

实现请求缓存可以显著减少API调用次数。使用WordPress的Transient API缓存API响应:


function cached_gemini_request($prompt, $api_key, $cache_hours = 24) {
    $cache_key = 'gemini_' . md5($prompt);
    $cached_response = get_transient($cache_key);
    
    if ($cached_response !== false) {
        return $cached_response;
    }
    
    $response = send_to_gemini_api($prompt, $api_key);
    
    if (strpos($response, '错误:') !== 0) {
        set_transient($cache_key, $response, $cache_hours  HOUR_IN_SECONDS);
    }
    
    return $response;
}

内容分段生成

对于长篇文章,采用分段生成策略可以避免单次请求过长导致的超时或高成本:


function generate_long_form_content($topic, $sections, $api_key) {
    $full_content = '';
    
    foreach ($sections as $section_title) {
        $prompt = "为一篇关于{$topic}的文章写'{$section_title}'部分,要求内容详细、专业,约300字";
        
        $section_content = cached_gemini_request($prompt, $api_key);
        
        if (strpos($section_content, '错误:') === 0) {
            $section_content = "<p>无法生成此部分内容:{$section_content}</p>";
        } else {
            $section_content = "<h2>{$section_title}</h2><p>{$section_content}</p>";
        }
        
        $full_content .= $section_content;
    }
    
    return $full_content;
}

// 使用示例
$topic = '人工智能在医疗领域的应用';
$sections = array(
    '引言',
    '诊断辅助',
    '药物研发',
    '患者监护',
    '挑战与展望'
);

$api_key = '你的Gemini_API密钥';
$article = generate_long_form_content($topic, $sections, $api_key);
echo $article;

API使用监控

创建一个简单的API使用监控仪表板,跟踪API调用次数和成本:


function add_api_usage_dashboard() {
    wp_add_dashboard_widget(
        'gemini_api_usage_widget',
        'Gemini API使用情况',
        'render_gemini_api_usage_widget'
    );
}
add_action('wp_dashboard_setup', 'add_api_usage_dashboard');

function render_gemini_api_usage_widget() {
    $usage_data = get_option('gemini_api_usage', array(
        'total_calls' => 0,
        'total_tokens' => 0,
        'estimated_cost' => 0,
        'daily_calls' => array(),
        'last_updated' => current_time('timestamp')
    ));
    
    echo '<h3>总体使用情况</h3>';
    echo '<table class="form-table">';
    echo '<tr><th>总调用次数</th><td>' . number_format($usage_data['total_calls']) . '</td></tr>';
    echo '<tr><th>总Token数</th><td>' . number_format($usage_data['total_tokens']) . '</td></tr>';
    echo '<tr><th>预估成本(美元)</th><td>$' . number_format($usage_data['estimated_cost'], 4) . '</td></tr>';
    echo '</table>';
    
    echo '<h3>最近7天使用趋势</h3>';
    echo '<div id="usage-chart" style="width:100%;height:200px;"></div>';
    
    // 准备图表数据
    $chart_data = array();
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-{$i} days"));
        $calls = isset($usage_data['daily_calls'][$date]) ? $usage_data['daily_calls'][$date] : 0;
        $chart_data[] = array('date' => $date, 'calls' => $calls);
    }
    
    echo '<script>';
    echo 'var chartData = ' . json_encode($chart_data) . ';';
    echo '// 这里可以添加图表渲染代码,例如使用Chart.js';
    echo '</script>';
}

function log_gemini_api_usage($tokens_used) {
    $usage_data = get_option('gemini_api_usage', array(
        'total_calls' => 0,
        'total_tokens' => 0,
        'estimated_cost' => 0,
        'daily_calls' => array(),
        'last_updated' => current_time('timestamp')
    ));
    
    $usage_data['total_calls']++;
    $usage_data['total_tokens'] += $tokens_used;
    
    // Gemini Pro定价:$0.0005/1K tokens(输入),$0.0015/1K tokens(输出)
    // 这里简化计算,假设平均$0.001/1K tokens
    $usage_data['estimated_cost'] += ($tokens_used / 1000)  0.001;
    
    $today = date('Y-m-d');
    if (!isset($usage_data['daily_calls'][$today])) {
        $usage_data['daily_calls'][$today] = 0;
    }
    $usage_data['daily_calls'][$today]++;
    
    // 只保留最近30天的数据
    $cutoff_date = date('Y-m-d', strtotime('-30 days'));
    foreach ($usage_data['daily_calls'] as $date => $calls) {
        if ($date < $cutoff_date) {
            unset($usage_data['daily_calls'][$date]);
        }
    }
    
    $usage_data['last_updated'] = current_time('timestamp');
    update_option('gemini_api_usage', $usage_data);
}

安全性与数据隐私保护

在WordPress中集成Gemini API时,确保数据安全和用户隐私至关重要。以下是几个关键的安全措施。

API密钥安全管理

避免将API密钥硬编码在主题或插件文件中。使用WordPress的选项API或环境变量存储密钥:


// 设置API密钥
function set_gemini_api_key() {
    if (!current_user_can('manage_options')) {
        return;
    }
    
    if (isset($_POST['gemini_api_key'])) {
        $api_key = sanitize_text_field($_POST['gemini_api_key']);
        update_option('gemini_api_key', $api_key);
        echo '<div class="notice notice-success"><p>API密钥已保存</p></div>';
    }
    
    $api_key = get_option('gemini_api_key', '');
    ?>
    <div class="wrap">
        <h1>Gemini API设置</h1>
        <form method="post">
            <table class="form-table">
                <tr>
                    <th scope="row">API密钥</th>
                    <td>
                        <input type="password" name="gemini_api_key" value="<?php echo esc_attr($api_key); ?>" class="regular-text">
                        <p class="description">输入你的Gemini API密钥。它将被安全存储。</p>
                    </td>
                </tr>
            </table>
            <?php submit_button('保存密钥'); ?>
        </form>
    </div>
    <?php
}

// 获取API密钥的函数
function get_gemini_api_key() {
    return get_option('gemini_api_key', '');
}

// 在使用API密钥的地方调用此函数
$api_key = get_gemini_api_key();
if (empty($api_key)) {
    // 处理API密钥未设置的情况
    return '错误:未设置Gemini API密钥';
}

用户数据脱敏

在向Gemini API发送数据前,确保移除或替换敏感信息:


function sanitize_content_for_gemini($content) {
    // 移除电子邮件地址
    $content = preg_replace('/b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}b/', '[EMAIL]', $content);
    
    // 移除电话号码
    $content = preg_replace('/bd{3}[-.]?d{3}[-.]?d{4}b/', '[PHONE]', $content);
    
    // 移除IP地址
    $content = preg_replace('/bd{1,3}.d{1,3}.d{1,3}.d{1,3}b/', '[IP]', $content);
    
    // 移除信用卡号(简化示例)
    $content = preg_replace('/bd{4}[- ]?d{4}[- ]?d{4}[- ]?d{4}b/', '[CREDIT_CARD]', $content);
    
    // 移除WordPress用户名
    $users = get_users();
    foreach ($users as $user) {
        $content = str_replace($user->user_login, '[USERNAME]', $content);
    }
    
    return $content;
}

// 使用示例
$raw_content = "联系我们的支持团队support@example.com或拨打555-123-4567。用户john_doe有问题。";
$sanitized_content = sanitize_content_for_gemini($raw_content);
// $sanitized_content 现在为:"联系我们的支持团队[EMAIL]或拨打[PHONE]。用户[USERNAME]有问题。"

访问控制与权限管理

限制Gemini API功能的使用权限,确保只有授权用户可以访问:


function add_gemini_capabilities() {
    $role = get_role('editor');
    if ($role) {
        $role->add_cap('use_gemini_api');
    }
    
    $role = get_role('administrator');
    if ($role) {
        $role->add_cap('use_gemini_api');
        $role->add_cap('manage_gemini_settings');
    }
}
add_action('admin_init', 'add_gemini_capabilities');

// 检查用户权限
function check_gemini_api_access() {
    if (!current_user_can('use_gemini_api')) {
        wp_die('您没有使用Gemini API的权限。');
    }
}

// 在API调用前添加权限检查
function secure_gemini_api_call($prompt) {
    check_gemini_api_access();
    
    $api_key = get_gemini_api_key();
    if (empty($api_key)) {
        return '错误:未配置Gemini API密钥';
    }
    
    $sanitized_prompt = sanitize_content_for_gemini($prompt);
    return cached_gemini_request($sanitized_prompt, $api_key);
}