在内容创作领域,AI 工具的出现极大提升了效率。本文将详细介绍如何在 WordPress 中接入 AI 能力实现自动生成文章,包含具体代码实现和操作步骤,即使是开发新手也能跟随操作。
已安装并运行的 WordPress 网站(建议 6.0 及以上版本)
PHP 7.4 及以上版本(需支持 cURL 扩展)
一个可用的 AI API 接口(本文以 OpenAI API 为例,需注册并获取 API 密钥)
基础的代码编辑工具(如 VS Code、Sublime Text)
通过 WordPress 后端代码调用 AI 接口,将用户输入的文章主题、关键词等参数传递给 AI 模型,获取生成的内容后,自动创建 WordPress 文章草稿并保存到数据库。
访问 OpenAI 官网 并注册账号
登录后进入「API Keys」页面(左侧菜单 → API Keys)
点击「Create new secret key」,输入名称(如 "WordPress AI")
复制生成的密钥(形如 sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx),注意:密钥仅显示一次,需妥善保存
为避免主题更新导致代码丢失,推荐通过自定义插件实现功能。
在 WordPress 安装目录的 /wp-content/plugins/ 下新建文件夹 ai-content-generator,并在该文件夹中创建 ai-content-generator.php 文件,添加以下基础代码:
<?php
if ( !defined( 'ABSPATH' ) ) {
exit;
}
在插件中添加设置页面,用于输入 API 密钥和配置生成参数。继续在 ai-content-generator.php 中添加:
add_action( 'admin_menu', 'ai_content_generator_add_menu' );
function ai_content_generator_add_menu() {
add_menu_page(
'AI 内容生成器',
'AI 内容生成',
'manage_options',
'ai-content-generator',
'ai_content_generator_settings_page',
'dashicons-welcome-write-blog',
6
);
}
function ai_content_generator_settings_page() {
if ( isset( $_POST['ai_save_settings'] ) && wp_verify_nonce( $_POST['ai_nonce'], 'ai_save_nonce' ) ) {
update_option( 'openai_api_key', sanitize_text_field( $_POST['openai_api_key'] ) );
update_option( 'ai_default_category', intval( $_POST['ai_default_category'] ) );
echo '<div class="notice notice-success"><p>设置已保存!</p></div>';
}
$api_key = get_option( 'openai_api_key', '' );
$default_category = get_option( 'ai_default_category', 1 );
?>
<div class="wrap">
<h1>AI 内容生成器设置</h1>
<form method="post">
<?php wp_nonce_field( 'ai_save_nonce', 'ai_nonce' ); ?>
<table class="form-table">
<tr>
<th scope="row"><label for="openai_api_key">OpenAI API 密钥</label></th>
<td>
<input type="text" name="openai_api_key" id="openai_api_key"
value="<?php echo esc_attr( $api_key ); ?>"
class="regular-text" placeholder="sk-xxxxxxxx...">
</td>
</tr>
<tr>
<th scope="row"><label for="ai_default_category">默认文章分类</label></th>
<td>
<?php
wp_dropdown_categories( array(
'name' => 'ai_default_category',
'id' => 'ai_default_category',
'selected' => $default_category,
'show_option_none' => '请选择分类',
'hide_empty' => false
) );
?>
</td>
</tr>
</table>
<p class="submit">
<input type="submit" name="ai_save_settings" class="button-primary" value="保存设置">
</p>
</form>
</div>
<?php
}
添加一个用于输入文章参数的页面,继续添加代码:
add_action( 'admin_menu', 'ai_content_generator_add_generator_page' );
function ai_content_generator_add_generator_page() {
add_submenu_page(
'ai-content-generator',
'生成 AI 文章',
'生成文章',
'manage_options',
'ai-generate-content',
'ai_content_generator_page'
);
}
function ai_content_generator_page() {
if ( !get_option( 'openai_api_key' ) ) {
echo '<div class="notice notice-error"><p>请先在 <a href="admin.php?page=ai-content-generator">设置</a> 中填写 OpenAI API 密钥!</p></div>';
return;
}
if ( isset( $_POST['generate_content'] ) && wp_verify_nonce( $_POST['generate_nonce'], 'generate_nonce' ) ) {
$title = sanitize_text_field( $_POST['article_title'] );
$keywords = sanitize_text_field( $_POST['article_keywords'] );
$length = intval( $_POST['article_length'] );
$content = generate_ai_content( $title, $keywords, $length );
if ( $content ) {
$post_id = wp_insert_post( array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'draft',
'post_type' => 'post',
'post_category' => array( get_option( 'ai_default_category', 1 ) )
) );
if ( $post_id ) {
echo '<div class="notice notice-success">';
echo '<p>文章生成成功!<a href="post.php?post=' . $post_id . '&action=edit">点击编辑</a></p>';
echo '</div>';
}
} else {
echo '<div class="notice notice-error"><p>生成失败,请重试!</p></div>';
}
}
?>
<div class="wrap">
<h1>生成 AI 文章</h1>
<form method="post">
<?php wp_nonce_field( 'generate_nonce', 'generate_nonce' ); ?>
<table class="form-table">
<tr>
<th scope="row"><label for="article_title">文章标题</label></th>
<td>
<input type="text" name="article_title" id="article_title"
class="regular-text" required placeholder="例如: WordPress 入门教程">
</td>
</tr>
<tr>
<th scope="row"><label for="article_keywords">关键词(用逗号分隔)</label></th>
<td>
<input type="text" name="article_keywords" id="article_keywords"
class="regular-text" placeholder="例如: WordPress, 教程, 入门">
</td>
</tr>
<tr>
<th scope="row"><label for="article_length">文章长度</label></th>
<td>
<select name="article_length" id="article_length" class="regular-text">
<option value="500">短(约 500 字)</option>
<option value="1000" selected>中(约 1000 字)</option>
<option value="2000">长(约 2000 字)</option>
</select>
</td>
</tr>
</table>
<p class="submit">
<input type="submit" name="generate_content" class="button-primary" value="生成文章">
</p>
</form>
</div>
<?php
}
实现调用 OpenAI API 的核心函数,添加以下代码:
function generate_ai_content( $title, $keywords, $length ) {
$api_key = get_option( 'openai_api_key' );
if ( !$api_key ) return false;
$prompt = "请写一篇关于「{$title}」的文章,";
if ( $keywords ) {
$prompt .= "关键词包括:{$keywords},";
}
$prompt .= "要求内容长度约 {$length} 字,结构清晰(包含小标题),语言流畅,内容原创。";
$args = array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
),
'body' => json_encode( array(
'model' => 'gpt-3.5-turbo',
'messages' => array(
array(
'role' => 'user',
'content' => $prompt
)
),
'temperature' => 0.7,
'max_tokens' => intval( $length * 1.5 ),
) ),
'timeout' => 60
);
$response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', $args );
if ( is_wp_error( $response ) ) {
error_log( 'AI 生成错误:' . $response->get_error_message() );
return false;
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( empty( $body['choices'][0]['message']['content'] ) ) {
error_log( 'AI 响应异常:' . print_r( $body, true ) );
return false;
}
$content = wpautop( $body['choices'][0]['message']['content'] );
return $content;
}
将 ai-content-generator 文件夹压缩为 ZIP 文件
登录 WordPress 后台 → 插件 → 安装插件 → 上传插件,选择压缩包并安装
安装完成后点击「启用插件」
在 WordPress 后台左侧菜单中找到「AI 内容生成」→「设置」,填入 OpenAI API 密钥并选择默认分类,点击「保存设置」
进入「AI 内容生成」→「生成文章」页面,填写:
文章标题(必填)
关键词(可选,用逗号分隔)
文章长度(短 / 中 / 长)
点击「生成文章」,等待 10-30 秒(根据文章长度)
生成成功后会显示「文章生成成功」提示,点击链接可直接编辑生成的草稿
添加内容预览:在生成文章前添加预览功能,让用户确认后再保存为草稿
支持多模型选择:扩展代码支持 GPT-4 等更多模型,可在设置页面添加模型选择项
增加生成历史:记录生成记录,方便查看和管理
添加图片生成:结合 DALL・E API 为文章自动生成配图
错误处理增强:添加更详细的错误提示(如 API 余额不足、网络错误等)
API 费用:OpenAI API 按使用量计费,需关注账户余额避免服务中断
内容审核:AI 生成内容可能存在不准确信息,发布前务必人工审核
密钥安全:不要在前端代码中暴露 API 密钥,本文实现的后端调用方式更安全
速率限制:免费账户有 API 调用频率限制,高频使用建议升级付费账户
通过以上步骤,你的 WordPress 网站已具备 AI 自动生成文章的能力。这一功能可以显著提升内容创作效率,尤其适合需要大量产出内容的博客、资讯类网站。记得根据实际需求调整代码,让 AI 工具更好地服务于你的创作流程。