AI生成工具与WordPress集成开发案例实践

WordPress与OpenAI API集成实现自动内容生成

WordPress作为全球最受欢迎的内容管理系统,与AI生成工具的集成已成为提升内容生产效率的重要途径。我们通过实际案例,展示如何将OpenAI的GPT模型API集成到WordPress网站,实现智能内容生成。

首先,你需要获取OpenAI API密钥。登录OpenAI平台后,在API密钥管理页面创建新密钥。请妥善保存此密钥,它将用于后续的API调用验证。

php
// 在WordPress主题的functions.php中添加以下代码
function openai_api_integration() {
$api_key = '你的OpenAI API密钥';
$prompt = '请写一篇关于人工智能发展趋势的文章';

$response = wp_remote_post('https://api.openai.com/v1/completions', array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'model' => 'text-davinci-003',
'prompt' => $prompt,
'max_tokens' => 1000,
'temperature' => 0.7
))
));

if (is_wp_error($response)) {
return 'API请求失败: ' . $response->get_error_message();
}

$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['choices'][0]['text'])) {
return $data['choices'][0]['text'];
}

return '无法生成内容';
}

上述代码实现了基本的OpenAI API调用功能。在实际应用中,你可能需要添加更多参数控制,如调整温度参数以控制内容创造性,或设置不同的模型以适应各种需求。

DeepSeek模型与WordPress表单集成实现智能问答

DeepSeek作为新兴的大语言模型,其强大的问答能力使其成为WordPress网站智能问答系统的理想选择。下面我们展示如何将DeepSeek API与WordPress表单插件集成,创建智能问答功能。

首先,在WordPress后台安装并激活一个表单插件,如WPForms或Contact Form 7。然后,创建一个新表单,包含问题和答案字段。

javascript
// 添加到主题的JavaScript文件中
jQuery(document).ready(function($) {
$('form').on('submit', function(e) {
e.preventDefault();

var question = $('question-field').val();
var apiKey = '你的DeepSeek API密钥';

$.ajax({
url: 'https://api.deepseek.com/v1/chat/completions',
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + apiKey
},
data: JSON.stringify({
model: 'deepseek-chat',
messages: [
{
role: 'user',
content: question
}
],
max_tokens: 1000,
temperature: 0.7
}),
success: function(response) {
if (response.choices && response.choices[0]) {
$('answer-field').val(response.choices[0].message.content);
}
},
error: function(xhr, status, error) {
console.error('API请求失败:', error);
$('answer-field').val('抱歉,无法处理您的请求。请稍后再试。');
}
});
});
});

注意:在实际部署中,API密钥不应直接暴露在前端JavaScript代码中。最佳实践是通过WordPress后端创建一个API代理端点,前端通过AJAX调用这个端点,由后端处理与DeepSeek API的通信。

豆包AI与WordPress媒体库集成实现智能图片生成

豆包AI的多模态生成能力使其成为WordPress媒体库的强大补充。以下案例展示如何通过豆包AI的API自动生成符合文章内容的图片,并上传到WordPress媒体库。

首先,创建一个WordPress插件来处理豆包AI API调用和媒体上传功能:

php
array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'prompt' => $prompt,
'n' => 1,
'size' => '1024x1024',
'response_format' => 'url'
))
));

if (is_wp_error($response)) {
return false;
}

$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['data'][0]['url'])) {
return $data['data'][0]['url'];
}

return false;
}

function doubao_upload_to_media_library($image_url, $post_id) {
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

$tmp = download_url($image_url);
$file_array = array(
'name' => basename($image_url),
'tmp_name' => $tmp
);

$media_id = media_handle_sideload($file_array, $post_id);

if (is_wp_error($media_id)) {
@unlink($file_array['tmp_name']);
return false;
}

return $media_id;
}

function doubao_auto_generate_featured_image($post_id) {
if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
return;
}

$post = get_post($post_id);
$prompt = '生成一张与以下文章主题相关的图片: ' . $post->post_title;

$image_url = doubao_generate_image($prompt);

if ($image_url) {
$media_id = doubao_upload_to_media_library($image_url, $post_id);

if ($media_id) {
set_post_thumbnail($post_id, $media_id);
}
}
}

add_action('save_post', 'doubao_auto_generate_featured_image', 10, 2);
?>

此插件会在保存文章时自动调用豆包AI API生成与文章主题相关的图片,并将其设置为文章的特色图片。请注意,豆包AI API的具体参数和响应格式可能会随着平台更新而变化,请参考最新的API文档进行调整。

通义千问与WordPress评论系统集成实现智能评论回复

通义千问是阿里巴巴开发的大语言模型,其强大的对话能力使其成为WordPress评论系统的理想补充。以下案例展示如何将通义千问API与WordPress评论系统集成,实现智能评论回复功能。

首先,创建一个自定义WordPress插件来处理通义千问API调用:

php
array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'model' => 'qwen-turbo',
'input' => array(
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
)
),
'parameters' => array(
'max_tokens' => 500,
'temperature' => 0.7
)
))
));

if (is_wp_error($response)) {
return false;
}

$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['output']['text'])) {
return $data['output']['text'];
}

return false;
}

function tongyi_auto_reply_comment($comment_id, $comment_approved) {
if ($comment_approved === 1 && !is_admin()) {
$comment = get_comment($comment_id);
$post_id = $comment->comment_post_ID;

// 避免回复自己的评论
if ($comment->user_id === get_current_user_id()) {
return;
}

$reply_text = tongyi_qianwen_generate_reply($comment->comment_content);

if ($reply_text) {
$reply_data = array(
'comment_post_ID' => $post_id,
'comment_author' => '网站助手',
'comment_author_email' => get_option('admin_email'),
'comment_content' => $reply_text,
'comment_type' => '',
'comment_parent' => $comment_id,
'user_id' => 0,
'comment_approved' => 1,
);

wp_insert_comment($reply_data);
}
}
}

add_action('comment_post', 'tongyi_auto_reply_comment', 10, 2);
?>

此插件会在新评论获得批准后,自动调用通义千问API生成一个智能回复,并将其作为对原评论的回复发布。请注意,通义千问API的具体参数和响应格式可能会随着平台更新而变化,请参考最新的API文档进行调整。

智谱AI与WordPress搜索系统集成实现智能搜索增强

智谱AI的语义理解能力使其成为WordPress搜索系统的理想增强工具。以下案例展示如何将智谱AI API与WordPress搜索系统集成,提供更智能的搜索结果和查询理解。

首先,创建一个自定义WordPress插件来处理智谱AI API调用和搜索增强:

php
array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'model' => 'glm-4',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'max_tokens' => 200,
'temperature' => 0.3
))
));

if (!is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['choices'][0]['message']['content'])) {
$enhanced_query = $data['choices'][0]['message']['content'];

// 将增强后的查询添加到原始查询中
$query->set('s', $original_query . ' ' . $enhanced_query);
}
}

return $query;
}

add_filter('pre_get_posts', 'zhipu_ai_enhance_search_query');

function zhipu_ai_generate_search_summary($posts) {
if (!is_search() || empty($posts)) {
return;
}

$api_key = '你的智谱AI API密钥';
$api_url = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';

$search_query = get_query_var('s');
$post_titles = array();

foreach ($posts as $post) {
$post_titles[] = $post->post_title;
}

$prompt = "基于搜索查询 '" . $search_query . "' 和以下相关文章标题,生成一个简短的搜索结果摘要:nn" . implode("n", $post_titles);

$response = wp_remote_post($api_url, array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'model' => 'glm-4',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'max_tokens' => 300,
'temperature' => 0.5
))
));

if (!is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['choices'][0]['message']['content'])) {
$summary = $data['choices'][0]['message']['content'];

// 在搜索结果页面顶部显示摘要
echo '

';
echo '

搜索结果摘要

';
echo '

' . esc_html($summary) . '

';
echo '

';
}
}
}

add_action('loop_start', 'zhipu_ai_generate_search_summary');
?>

此插件通过两种方式增强WordPress搜索功能:首先,它使用智谱AI API优化搜索查询,提取关键词并提供相关术语;其次,它生成搜索结果摘要,帮助用户更快地理解搜索结果。请注意,智谱AI API的具体参数和响应格式可能会随着平台更新而变化,请参考最新的API文档进行调整。

多模型AI工具集成与WordPress自动化工作流

将多个AI生成工具集成到WordPress中,可以创建强大的自动化工作流。以下案例展示如何结合OpenAI、豆包AI和通义千问等多个AI模型,构建一个完整的内容创作和发布流程。

首先,创建一个WordPress插件来管理多模型AI集成:

php
openai_api_key = '你的OpenAI API密钥';
$this->doubao_api_key = '你的豆包AI API密钥';
$this->tongyi_api_key = '你的通义千问API密钥';

add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
}

public function add_admin_menu() {
add_menu_page(
'AI内容工作流',
'AI内容工作流',
'manage_options',
'ai-content-workflow',
array($this, 'admin_page'),
'dashicons-edit-page'
);
}

public function register_settings() {
register_setting('ai_workflow_settings', 'ai_workflow_openai_key');
register_setting('ai_workflow_settings', 'ai_workflow_doubao_key');
register_setting('ai_workflow_settings', 'ai_workflow_tongyi_key');
}

public function admin_page() {
?>

AI内容工作流

OpenAI API密钥 <input type="text" name="ai_workflow_openai_key" value="" />
豆包AI API密钥 <input type="text" name="ai_workflow_doubao_key" value="" />
通义千问API密钥 <input type="text" name="ai_workflow_tongyi_key" value="" />

创建新内容

内容主题
内容类型

博客文章
产品评测
教程
新闻

目标受众

generate_content_workflow(
sanitize_text_field($_POST['content_topic']),
sanitize_text_field($_POST['content_type']),
sanitize_text_field($_POST['target_audience'])
);
}
?>

generate_outline_with_openai($topic, $type, $audience);

// 步骤2: 使用通义千问根据大纲生成完整内容
$content = $this->generate_content_with_tongyi($outline, $type);

// 步骤3: 使用豆包AI生成相关图片
$image_prompt = $this->generate_image_prompt_with_openai($topic, $type);
$image_url = $this->generate_image_with_doubao($image_prompt);

// 步骤4: 创建WordPress文章
$post_id = $this->create_wordpress_post($topic, $content, $image_url);

// 显示结果
echo '

';
echo '

内容已成功生成并发布为文章: 查看文章

AI生成工具与WordPress集成开发案例实践';
echo '

';
}

private function generate_outline_with_openai($topic, $type, $audience) {
$api_key = get_option('ai_workflow_openai_key', $this->openai_api_key);
$prompt = "请为一篇关于{$topic}的{$type}创建一个详细的内容大纲,目标受众是{$audience}。大纲应包含引言、主要部分和结论。";

$response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'model' => 'gpt-4',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'max_tokens' => 1000,
'temperature' => 0.7
))
));

if (!is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['choices'][0]['message']['content'])) {
return $data['choices'][0]['message']['content'];
}
}

return false;
}

private function generate_content_with_tongyi($outline, $type) {
$api_key = get_option('ai_workflow_tongyi_key', $this->tongyi_api_key);
$prompt = "请根据以下大纲,创建一篇完整的{$type}内容:nn{$outline}";

$response = wp_remote_post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'model' => 'qwen-turbo',
'input' => array(
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
)
),
'parameters' => array(
'max_tokens' => 2000,
'temperature' => 0.7
)
))
));

if (!is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['output']['text'])) {
return $data['output']['text'];
}
}

return false;
}

private function generate_image_prompt_with_openai($topic, $type) {
$api_key = get_option('ai_workflow_openai_key', $this->openai_api_key);
$prompt = "请为一篇关于{$topic}的{$type}创建一个详细的图片生成提示词,描述适合作为文章特色图片的视觉元素。";

$response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'model' => 'gpt-4',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'max_tokens' => 200,
'temperature' => 0.7
))
));

if (!is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['choices'][0]['message']['content'])) {
return $data['choices'][0]['message']['content'];
}
}

return false;
}

private function generate_image_with_doubao($prompt) {
$api_key = get_option('ai_workflow_doubao_key', $this->doubao_api_key);
$api_url = 'https://api.doubao.com/v1/images/generations';

$response = wp_remote_post($api_url, array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'prompt' => $prompt,
'n' => 1,
'size' => '1024x1024',
'response_format' => 'url'
))
));

if (!is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (isset($data['data'][0]['url'])) {
return $data['data'][0]['url'];
}
}

return false;
}

private function create_wordpress_post($title, $content, $image_url) {
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

// 上传图片
$tmp = download_url($image_url);
$file_array = array(
'name' => basename($image_url),
'tmp_name' => $tmp
);

$media_id = media_handle_sideload($file_array, 0);

// 创建文章
$post_data = array(
'post_title' => wp_strip_all_tags($title),
'post_content' => $content,
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_category' => array(1) // 默认分类
);

$post_id = wp_insert_post($post_data);

// 设置特色图片
if (!is_wp_error($media_id)) {
set_post_thumbnail($post_id, $media_id);
}

return $post_id;
}
}

new Multi_AI_Content_Workflow();
?>

此插件创建了一个完整的多模型AI内容工作流,包括:
1. 使用OpenAI生成内容大纲
2. 使用通义千问根据大纲生成完整内容
3. 使用OpenAI生成图片提示词
4. 使用豆包AI生成相关图片
5. 创建WordPress文章并设置特色图片

这个工作流展示了如何将多个AI模型集成到WordPress中,创建一个自动化的内容创作和发布流程。请注意,各个AI模型API的具体参数和响应格式可能会随着平台更新而变化,请参考最新的API文档进行调整。

AI生成工具集成中的错误处理与性能优化

在集成AI生成工具到WordPress时,错误处理和性能优化是确保系统稳定运行的关键因素。以下是一些常见问题的解决方案和性能优化策略。

API请求失败处理

当AI模型API请求失败时,适当的错误处理可以防止整个系统崩溃。以下是一个健壮的错误处理示例:

php
function safe_ai_api_request($url, $args, $fallback_response = '') {
$response = wp_remote_post($url, $args);

if (is_wp_error($response)) {
error_log('AI API请求错误: ' . $response->get_error_message());
return $fallback_response;
}

$response_code = wp_remote_retrieve_response_code($response);

if ($response_code !== 200) {
error_log('AI API返回错误状态码: ' . $response_code);
return $fallback_response;
}

$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (json_last_error() !== JSON_ERROR_NONE) {
error_log('AI API响应解析错误: ' . json_last_error_msg());
return $fallback_response;
}

return $data;
}

API限流与请求缓存

AI模型API通常有请求频率限制,合理的请求缓存可以避免超出限制并提高响应速度:

php
class AI_API_Cache {
private $cache_group = 'ai_api_responses';
private $cache_expiration = 3600; // 1小时缓存

public function get_cached_response($cache_key) {
return wp_cache_get($cache_key, $this->cache_group);
}

public function set_cached_response($cache_key, $response) {
wp_cache_set($cache_key, $response, $this->cache_group, $this->cache_expiration);
}

public function make_request_with_cache($url, $args, $cache_key, $fallback_response = '') {
$cached_response = $this->get_cached_response($cache_key);

if ($cached_response !== false) {
return $cached_response;
}

$response = safe_ai_api_request($url, $args, $fallback_response);

if ($response !== $fallback_response) {
$this->set_cached_response($cache_key, $response);
}

return $response;
}
}

异步处理长时间任务

AI生成内容可能需要较长时间,使用WordPress的异步处理机制可以避免用户等待:

php
function schedule_ai_content_generation($post_id, $prompt) {
$args = array(
'post_id' => $post_id,
'prompt' => $prompt
);

wp_schedule_single_event(time() + 60, 'generate_ai_content_event', $args);
}

add_action('generate_ai_content_event', 'execute_ai_content_generation');

function execute_ai_content_generation($post_id, $prompt) {
$api_key = '你的AI API密钥';
$api_url = 'https://api.example.com/v1/generate';

$args = array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode(array(
'prompt' => $prompt,
'max_tokens' => 1000
)),
'timeout' => 60 // 增加超时时间
);

$response = safe_ai_api_request($api_url, $args);

if ($response && isset($response['generated_text'])) {
$post = array(
'ID' => $post_id,
'post_content' => $response['generated_text']
);

wp_update_post($post);
}
}

资源使用监控与限制

监控AI API的使用情况,避免超出预算限制:

php
class AI_API_Usage_Monitor {
private $option_name = 'ai_api_usage_stats';
private $daily_limit = 1000; // 每日请求限制

public function __construct() {
$this->reset_usage_if_new_day();
}

private function reset_usage_if_new_day() {
$stats = get_option($this->option_name, array());
$last_reset_date = isset($stats['last_reset_date']) ? $stats['last_reset_date'] : date('Y-m-d');

if ($last_reset_date !== date('Y-m-d')) {
$stats = array(
'request_count' => 0,
'tokens_used' => 0,
'last_reset_date' => date('Y-m-d')
);

update_option($this->option_name, $stats);
}
}

public function can_make_request() {
$stats = get_option($this->option_name, array());
$request_count = isset($stats['request_count']) ? $stats['request_count'] : 0;

return $request_count daily_limit;
}

public function record_request($tokens_used = 0) {
$stats = get_option($this->option_name, array());

$stats['request_count'] = isset($stats['request_count']) ? $stats['request_count'] + 1 : 1;
$stats['tokens_used'] = isset($stats['tokens_used']) ? $stats['tokens_used'] + $tokens_used : $tokens_used;

update_option($this->option_name, $stats);
}

public function get_usage_stats() {
return get_option($this->option_name, array());
}
}

通过以上错误处理和性能优化策略,你可以确保AI生成工具与WordPress的集成更加稳定和高效。这些技术可以帮助你避免常见的集成问题,提高用户体验,并控制API使用成本。