WordPress如何集成ChatGPT实现自动生成文章的API开发教程
- Linkreate AI插件 文章
- 2025-08-30 21:40:06
- 14阅读
准备工作:获取OpenAI API密钥
在开始WordPress与ChatGPT的集成之前,首先需要获取OpenAI API密钥。访问OpenAI官方网站,登录或创建账户后,导航至API密钥管理页面。点击"Create new secret key"按钮生成新的API密钥。请妥善保存此密钥,因为它只会在创建时显示一次,之后无法再次查看。
安装必要的WordPress插件
为了实现WordPress与ChatGPT的集成,我们需要安装一个支持API连接的插件。在WordPress后台,导航至"插件" > "安装插件",搜索"WP Webhooks"或"Custom Post Type UI"等支持API集成的插件。安装并激活所选插件。
创建自定义API端点
在WordPress中创建自定义API端点是连接ChatGPT的关键步骤。以下是通过functions.php文件添加自定义API端点的代码:
// 添加自定义API端点
add_action('rest_api_init', function () {
register_rest_route('chatgpt/v1', '/generate', array(
'methods' => 'POST',
'callback' => 'chatgpt_generate_content',
'permission_callback' => function () {
return current_user_can('edit_posts');
}
));
});
// 处理内容生成请求
function chatgpt_generate_content($request) {
$params = $request->get_json_params();
$prompt = isset($params['prompt']) ? sanitize_text_field($params['prompt']) : '';
if (empty($prompt)) {
return new WP_Error('no_prompt', '提示词不能为空', array('status' => 400));
}
$api_key = '你的OpenAI API密钥';
$api_url = 'https://api.openai.com/v1/chat/completions';
$body = array(
'model' => 'gpt-3.5-turbo',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'max_tokens' => 1000,
'temperature' => 0.7
);
$args = array(
'body' => json_encode($body),
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'timeout' => 30
);
$response = wp_remote_post($api_url, $args);
if (is_wp_error($response)) {
return new WP_Error('api_error', $response->get_error_message(), array('status' => 500));
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['error'])) {
return new WP_Error('openai_error', $data['error']['message'], array('status' => 500));
}
$generated_content = $data['choices'][0]['message']['content'];
return array(
'success' => true,
'content' => $generated_content
);
}
创建前端界面
为了方便用户使用ChatGPT生成内容,我们需要在WordPress后台创建一个前端界面。以下代码将添加一个管理页面:
// 添加管理菜单
add_action('admin_menu', 'chatgpt_admin_menu');
function chatgpt_admin_menu() {
add_menu_page(
'ChatGPT内容生成器',
'ChatGPT生成器',
'edit_posts',
'chatgpt-generator',
'chatgpt_admin_page',
'dashicons-edit-page'
);
}
// 管理页面内容
function chatgpt_admin_page() {
?>
ChatGPT内容生成器
jQuery(document).ready(function($) {
$('generate-content').on('click', function() {
var prompt = $('chatgpt-prompt').val();
var resultContainer = $('chatgpt-result');
if (!prompt) {
resultContainer.('请输入提示词
');
return;
}
resultContainer.('正在生成内容,请稍候...
');
$.ajax({
url: '',
method: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', '');
},
data: JSON.stringify({
prompt: prompt
}),
contentType: 'application/json',
success: function(response) {
if (response.success) {
resultContainer.('内容生成成功!
');
} else {
resultContainer.('生成失败:' + response.message + '
');
}
},
error: function(xhr) {
var response = xhr.responseJSON;
var message = response.message || '未知错误';
resultContainer.('请求失败:' + message + '
');
}
});
});
});
<?php
}
实现自动发布功能
为了实现生成内容后自动发布为文章,我们需要扩展API端点和前端界面。以下是修改后的代码:
// 修改API端点以支持自动发布
function chatgpt_generate_content($request) {
$params = $request->get_json_params();
$prompt = isset($params['prompt']) ? sanitize_text_field($params['prompt']) : '';
$auto_publish = isset($params['auto_publish']) ? (bool)$params['auto_publish'] : false;
$post_title = isset($params['post_title']) ? sanitize_text_field($params['post_title']) : '';
if (empty($prompt)) {
return new WP_Error('no_prompt', '提示词不能为空', array('status' => 400));
}
$api_key = '你的OpenAI API密钥';
$api_url = 'https://api.openai.com/v1/chat/completions';
$body = array(
'model' => 'gpt-3.5-turbo',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'max_tokens' => 2000,
'temperature' => 0.7
);
$args = array(
'body' => json_encode($body),
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'timeout' => 30
);
$response = wp_remote_post($api_url, $args);
if (is_wp_error($response)) {
return new WP_Error('api_error', $response->get_error_message(), array('status' => 500));
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['error'])) {
return new WP_Error('openai_error', $data['error']['message'], array('status' => 500));
}
$generated_content = $data['choices'][0]['message']['content'];
$post_id = null;
if ($auto_publish) {
$post_data = array(
'post_title' => $post_title ? $post_title : wp_trim_words($generated_content, 10),
'post_content' => $generated_content,
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'post'
);
$post_id = wp_insert_post($post_data);
if (is_wp_error($post_id)) {
return new WP_Error('publish_error', $post_id->get_error_message(), array('status' => 500));
}
}
return array(
'success' => true,
'content' => $generated_content,
'post_id' => $post_id
);
}
添加定时任务功能
为了实现定时自动生成文章,我们需要添加WordPress定时任务功能:
// 添加定时任务
add_action('wp', 'chatgpt_schedule_generation');
function chatgpt_schedule_generation() {
if (!wp_next_scheduled('chatgpt_daily_generation')) {
wp_schedule_event(time(), 'daily', 'chatgpt_daily_generation');
}
}
// 定时任务回调函数
add_action('chatgpt_daily_generation', 'chatgpt_execute_scheduled_generation');
function chatgpt_execute_scheduled_generation() {
$prompts = get_option('chatgpt_scheduled_prompts', array());
foreach ($prompts as $prompt) {
$api_key = '你的OpenAI API密钥';
$api_url = 'https://api.openai.com/v1/chat/completions';
$body = array(
'model' => 'gpt-3.5-turbo',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'max_tokens' => 2000,
'temperature' => 0.7
);
$args = array(
'body' => json_encode($body),
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'timeout' => 30
);
$response = wp_remote_post($api_url, $args);
if (!is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (!isset($data['error'])) {
$generated_content = $data['choices'][0]['message']['content'];
$post_data = array(
'post_title' => wp_trim_words($generated_content, 10),
'post_content' => $generated_content,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post'
);
wp_insert_post($post_data);
}
}
}
}
添加API使用限制和监控
为了避免API过度使用,我们需要添加使用限制和监控功能:
// 添加API使用限制
function chatgpt_check_api_limit($user_id) {
$today = date('Y-m-d');
$usage = get_user_meta($user_id, 'chatgpt_api_usage_' . $today, true);
if (!$usage) {
$usage = 0;
}
$limit = get_option('chatgpt_daily_limit', 50);
if ($usage >= $limit) {
return false;
}
return true;
}
// 更新API使用计数
function chatgpt_update_api_usage($user_id) {
$today = date('Y-m-d');
$usage = get_user_meta($user_id, 'chatgpt_api_usage_' . $today, true);
if (!$usage) {
$usage = 0;
}
$usage++;
update_user_meta($user_id, 'chatgpt_api_usage_' . $today, $usage);
}
// 修改API端点以包含使用限制
function chatgpt_generate_content($request) {
$user_id = get_current_user_id();
if (!chatgpt_check_api_limit($user_id)) {
return new WP_Error('limit_exceeded', '今日API调用次数已达上限', array('status' => 429));
}
// 原有代码...
chatgpt_update_api_usage($user_id);
// 原有代码...
}
集成Webhooks实现自动化工作流
为了进一步扩展功能,我们可以添加Webhooks支持,使WordPress能够与其他系统进行集成:
// 添加Webhooks端点
add_action('rest_api_init', function () {
register_rest_route('chatgpt/v1', '/webhook', array(
'methods' => 'POST',
'callback' => 'chatgpt_webhook_handler',
'permission_callback' => '__return_true'
));
});
// Webhook处理函数
function chatgpt_webhook_handler($request) {
$params = $request->get_json_params();
$event = isset($params['event']) ? sanitize_text_field($params['event']) : '';
$data = isset($params['data']) ? $params['data'] : array();
// 验证Webhook签名
$signature = $request->get_header('X-ChatGPT-Signature');
$webhook_secret = get_option('chatgpt_webhook_secret');
if (!$signature || !$webhook_secret) {
return new WP_Error('invalid_signature', '无效的签名', array('status' => 401));
}
$payload = $request->get_body();
$expected_signature = hash_hmac('sha256', $payload, $webhook_secret);
if (!hash_equals($expected_signature, $signature)) {
return new WP_Error('invalid_signature', '签名验证失败', array('status' => 401));
}
// 处理不同的事件类型
switch ($event) {
case 'generate_content':
if (isset($data['prompt']) && !empty($data['prompt'])) {
$prompt = sanitize_text_field($data['prompt']);
$post_title = isset($data['title']) ? sanitize_text_field($data['title']) : '';
// 调用内容生成函数
$result = chatgpt_generate_and_publish($prompt, $post_title);
return array(
'success' => true,
'post_id' => $result
);
}
break;
case 'batch_generate':
if (isset($data['prompts']) && is_array($data['prompts'])) {
$post_ids = array();
foreach ($data['prompts'] as $item) {
if (isset($item['prompt']) && !empty($item['prompt'])) {
$prompt = sanitize_text_field($item['prompt']);
$post_title = isset($item['title']) ? sanitize_text_field($item['title']) : '';
$post_id = chatgpt_generate_and_publish($prompt, $post_title);
if ($post_id && !is_wp_error($post_id)) {
$post_ids[] = $post_id;
}
}
}
return array(
'success' => true,
'post_ids' => $post_ids
);
}
break;
}
return new WP_Error('invalid_event', '不支持的事件类型', array('status' => 400));
}
// 内容生成和发布辅助函数
function chatgpt_generate_and_publish($prompt, $post_title = '') {
$api_key = '你的OpenAI API密钥';
$api_url = 'https://api.openai.com/v1/chat/completions';
$body = array(
'model' => 'gpt-3.5-turbo',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'max_tokens' => 2000,
'temperature' => 0.7
);
$args = array(
'body' => json_encode($body),
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'timeout' => 30
);
$response = wp_remote_post($api_url, $args);
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['error'])) {
return false;
}
$generated_content = $data['choices'][0]['message']['content'];
$post_data = array(
'post_title' => $post_title ? $post_title : wp_trim_words($generated_content, 10),
'post_content' => $generated_content,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post'
);
return wp_insert_post($post_data);
}
实现内容模板和自定义字段
为了使生成的内容更加符合网站需求,我们可以添加内容模板和自定义字段支持:
// 添加内容模板设置
add_action('admin_init', 'chatgpt_template_settings');
function chatgpt_template_settings() {
register_setting('chatgpt_options', 'chatgpt_content_template');
add_settings_section(
'chatgpt_template_section',
'内容模板设置',
'chatgpt_template_section_callback',
'chatgpt_options'
);
add_settings_field(
'chatgpt_content_template',
'内容模板',
'chatgpt_template_field_callback',
'chatgpt_options',
'chatgpt_template_section'
);
}
function chatgpt_template_section_callback() {
echo '设置ChatGPT生成内容的模板格式。可以使用{content}作为占位符表示生成的内容。';
}
function chatgpt_template_field_callback() {
$template = get_option('chatgpt_content_template', '{title}
{content}
');
echo '';
}
// 修改内容生成函数以支持模板
function chatgpt_generate_content($request) {
// 原有代码...
$template = get_option('chatgpt_content_template', '{title}
{content}
');
$title = wp_trim_words($generated_content, 10);
$formatted_content = str_replace(
array('{title}', '{content}'),
array($title, $generated_content),
$template
);
// 原有代码...
}
通过以上步骤,我们已经完成了WordPress与ChatGPT的API集成,实现了自动生成文章的功能。这个集成包括API密钥配置、自定义端点创建、前端界面开发、自动发布功能、定时任务、API使用限制、Webhooks集成以及内容模板支持。这些功能共同构成了一个完整的AI内容生成系统,可以大大提高WordPress网站的内容生产效率。