文章目录[隐藏]
WordPress高级教程:开发集成AI的智能内容创作与辅助写作工具
引言:WordPress在AI时代的新机遇
WordPress作为全球最流行的内容管理系统,占据了互联网超过43%的网站份额。随着人工智能技术的飞速发展,将AI能力集成到WordPress平台已成为提升内容创作效率和质量的重要趋势。本教程将深入探讨如何通过WordPress代码二次开发,构建集成AI的智能内容创作与辅助写作工具,同时实现常用互联网小工具功能,为网站管理员和内容创作者提供全方位的智能解决方案。
在当今信息爆炸的时代,内容创作者面临着日益增长的创作压力和质量要求。AI技术的引入不仅可以自动化部分创作流程,还能提供智能建议、优化内容结构、增强可读性,甚至生成个性化内容。通过将AI能力与WordPress的强大扩展性相结合,我们可以打造出真正智能化的内容创作生态系统。
第一部分:WordPress开发环境搭建与AI技术选型
1.1 WordPress开发环境配置
要开始WordPress高级开发,首先需要搭建专业的开发环境。推荐使用以下配置:
- 本地开发环境:使用Local by Flywheel、XAMPP或Docker容器化环境
- 代码编辑器:VS Code配合PHP Intelephense、WordPress代码片段等扩展
- 调试工具:安装Query Monitor、Debug Bar等WordPress调试插件
- 版本控制:Git配合GitHub或GitLab进行代码管理
对于AI集成开发,还需要确保服务器环境满足以下要求:
- PHP 7.4或更高版本
- 至少256MB内存限制(建议512MB以上)
- 支持cURL扩展
- 可选的GPU加速支持(用于本地AI模型运行)
1.2 AI技术选型与集成策略
选择合适的AI技术是项目成功的关键。根据功能需求和资源情况,可以考虑以下方案:
云端AI服务集成:
- OpenAI GPT系列API:用于内容生成、改写、摘要
- Google Cloud Natural Language:用于情感分析、实体识别
- IBM Watson:用于语气分析、内容优化
- 国内可选:百度文心、阿里通义、腾讯混元等
本地AI模型部署:
- 使用Transformers库部署轻量级模型
- 利用ONNX Runtime优化推理性能
- 考虑使用GPT-2、BERT等开源模型
混合方案:
- 核心功能使用云端API保证质量
- 辅助功能使用本地模型降低成本
- 敏感数据处理使用本地模型确保隐私
第二部分:WordPress插件架构设计与AI集成
2.1 智能内容创作插件架构设计
创建一个名为"AI Content Creator Pro"的WordPress插件,采用模块化设计:
/*
Plugin Name: AI Content Creator Pro
Plugin URI: https://yourwebsite.com/ai-content-creator
Description: 集成AI的智能内容创作与辅助写作工具
Version: 1.0.0
Author: Your Name
License: GPL v2 or later
*/
// 主插件类
class AI_Content_Creator_Pro {
private static $instance = null;
private $ai_services = [];
private $tools_manager;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->define_constants();
$this->init_hooks();
$this->load_dependencies();
}
private function define_constants() {
define('AICC_VERSION', '1.0.0');
define('AICC_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('AICC_PLUGIN_URL', plugin_dir_url(__FILE__));
define('AICC_AI_CACHE_EXPIRY', 24 * HOUR_IN_SECONDS);
}
private function init_hooks() {
add_action('init', [$this, 'init_plugin']);
add_action('admin_menu', [$this, 'add_admin_menu']);
add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
add_action('add_meta_boxes', [$this, 'add_content_ai_metabox']);
}
private function load_dependencies() {
// 加载核心模块
require_once AICC_PLUGIN_DIR . 'includes/class-ai-service-manager.php';
require_once AICC_PLUGIN_DIR . 'includes/class-content-generator.php';
require_once AICC_PLUGIN_DIR . 'includes/class-writing-assistant.php';
require_once AICC_PLUGIN_DIR . 'includes/class-tools-manager.php';
require_once AICC_PLUGIN_DIR . 'includes/class-utilities.php';
// 加载AI服务适配器
require_once AICC_PLUGIN_DIR . 'includes/ai-services/class-openai-adapter.php';
require_once AICC_PLUGIN_DIR . 'includes/ai-services/class-local-ai-adapter.php';
// 加载工具模块
require_once AICC_PLUGIN_DIR . 'includes/tools/class-seo-analyzer.php';
require_once AICC_PLUGIN_DIR . 'includes/tools/class-readability-checker.php';
require_once AICC_PLUGIN_DIR . 'includes/tools/class-plagiarism-checker.php';
}
public function init_plugin() {
$this->ai_services = AI_Service_Manager::get_available_services();
$this->tools_manager = new Tools_Manager();
// 初始化短代码
$this->init_shortcodes();
}
// ... 其他方法
}
2.2 AI服务管理器实现
AI服务管理器负责统一接口调用不同的AI服务:
class AI_Service_Manager {
private static $services = [];
public static function register_service($service_id, $class_name, $config = []) {
self::$services[$service_id] = [
'class' => $class_name,
'config' => $config,
'instance' => null
];
}
public static function get_service($service_id = 'default') {
if (!isset(self::$services[$service_id])) {
return false;
}
if (null === self::$services[$service_id]['instance']) {
$class_name = self::$services[$service_id]['class'];
self::$services[$service_id]['instance'] = new $class_name(
self::$services[$service_id]['config']
);
}
return self::$services[$service_id]['instance'];
}
public static function get_available_services() {
$services = [];
// 检查OpenAI配置
$openai_key = get_option('aicc_openai_api_key', '');
if (!empty($openai_key)) {
self::register_service('openai', 'OpenAI_Adapter', [
'api_key' => $openai_key,
'model' => get_option('aicc_openai_model', 'gpt-3.5-turbo'),
'max_tokens' => get_option('aicc_openai_max_tokens', 1000)
]);
$services['openai'] = 'OpenAI GPT';
}
// 检查本地AI服务
if (self::is_local_ai_available()) {
self::register_service('local', 'Local_AI_Adapter', [
'model_path' => get_option('aicc_local_model_path', ''),
'use_gpu' => get_option('aicc_use_gpu', false)
]);
$services['local'] = '本地AI模型';
}
return $services;
}
private static function is_local_ai_available() {
// 检查本地AI环境是否可用
$model_path = get_option('aicc_local_model_path', '');
return !empty($model_path) && file_exists($model_path);
}
public static function generate_content($prompt, $options = [], $service_id = 'default') {
$service = self::get_service($service_id);
if (!$service) {
return new WP_Error('service_unavailable', 'AI服务不可用');
}
// 检查缓存
$cache_key = 'aicc_content_' . md5($prompt . serialize($options) . $service_id);
$cached = get_transient($cache_key);
if ($cached !== false) {
return $cached;
}
// 调用AI服务
$result = $service->generate($prompt, $options);
// 缓存结果
if (!is_wp_error($result)) {
set_transient($cache_key, $result, AICC_AI_CACHE_EXPIRY);
}
return $result;
}
}
第三部分:核心功能实现 - 智能内容创作
3.1 AI内容生成器实现
内容生成器是插件的核心功能,支持多种内容类型生成:
class Content_Generator {
private $ai_service;
public function __construct($service_id = 'default') {
$this->ai_service = AI_Service_Manager::get_service($service_id);
}
public function generate_blog_post($topic, $options = []) {
$default_options = [
'tone' => 'informative',
'length' => 'medium',
'target_audience' => 'general',
'include_seo_keywords' => true,
'structure' => 'introduction-body-conclusion'
];
$options = wp_parse_args($options, $default_options);
// 构建AI提示词
$prompt = $this->build_blog_post_prompt($topic, $options);
// 调用AI生成内容
$content = AI_Service_Manager::generate_content($prompt, [
'max_tokens' => $this->get_token_length($options['length']),
'temperature' => 0.7,
'top_p' => 0.9
]);
if (is_wp_error($content)) {
return $content;
}
// 后处理内容
$processed_content = $this->post_process_content($content, $options);
return [
'title' => $this->extract_title($processed_content),
'content' => $processed_content,
'excerpt' => $this->generate_excerpt($processed_content),
'meta_description' => $this->generate_meta_description($processed_content),
'tags' => $this->extract_tags($processed_content, $topic)
];
}
private function build_blog_post_prompt($topic, $options) {
$prompt_templates = [
'informative' => "请以专业、 informative 的语气撰写一篇关于 {$topic} 的博客文章。",
'conversational' => "请以对话式、友好的语气撰写一篇关于 {$topic} 的博客文章。",
'persuasive' => "请以有说服力的语气撰写一篇关于 {$topic} 的博客文章,旨在说服读者采取行动。"
];
$tone = isset($prompt_templates[$options['tone']]) ?
$prompt_templates[$options['tone']] :
$prompt_templates['informative'];
$length_instructions = [
'short' => '文章长度约500字左右,内容简洁明了。',
'medium' => '文章长度约1000-1500字,内容详实。',
'long' => '文章长度约2000字以上,内容全面深入。'
];
$length = isset($length_instructions[$options['length']]) ?
$length_instructions[$options['length']] :
$length_instructions['medium'];
$structure_guide = "文章结构应包括:引言、主体内容(分几个小节阐述)和结论。";
$seo_instruction = $options['include_seo_keywords'] ?
"请自然地包含相关关键词,但不要堆砌。" : "";
$audience_instruction = "目标读者是{$options['target_audience']},请使用他们容易理解的语言。";
return "{$tone} {$length} {$structure_guide} {$seo_instruction} {$audience_instruction}";
}
private function get_token_length($length) {
$lengths = [
'short' => 800,
'medium' => 1500,
'long' => 3000
];
return isset($lengths[$length]) ? $lengths[$length] : $lengths['medium'];
}
public function generate_content_ideas($seed_topic, $count = 5) {
$prompt = "基于主题'{$seed_topic}',生成{$count}个相关的博客文章创意。每个创意包括标题和简要描述。";
$ideas = AI_Service_Manager::generate_content($prompt, [
'max_tokens' => 800,
'temperature' => 0.8
]);
if (is_wp_error($ideas)) {
return $ideas;
}
return $this->parse_content_ideas($ideas);
}
public function rewrite_content($original_content, $options = []) {
$default_options = [
'purpose' => 'improve_clarity',
'tone' => null,
'simplify' => false
];
$options = wp_parse_args($options, $default_options);
$purpose_instructions = [
'improve_clarity' => '提高内容清晰度和可读性',
'seo_optimization' => '优化SEO,自然地加入关键词',
'change_tone' => '改变文章语气为' . ($options['tone'] ?: '专业'),
'summarize' => '总结内容,保留核心信息'
];
$instruction = isset($purpose_instructions[$options['purpose']]) ?
$purpose_instructions[$options['purpose']] :
'改进内容';
$prompt = "请重新改写以下内容,要求:{$instruction}。" .
($options['simplify'] ? "请简化语言,使其更易理解。" : "") .
"nn原文:n{$original_content}";
return AI_Service_Manager::generate_content($prompt, [
'max_tokens' => strlen($original_content) * 1.5,
'temperature' => 0.6
]);
}
// ... 其他内容生成方法
}
3.2 智能写作助手实现
写作助手在编辑器中提供实时AI辅助:
class Writing_Assistant {
public function __construct() {
add_action('admin_init', [$this, 'init_writing_assistant']);
}
public function init_writing_assistant() {
// 添加编辑器按钮
add_filter('mce_buttons', [$this, 'add_tinymce_buttons']);
add_filter('mce_external_plugins', [$this, 'add_tinymce_plugins']);
// 添加Gutenberg块
if (function_exists('register_block_type')) {
add_action('init', [$this, 'register_gutenberg_blocks']);
}
// 添加AJAX处理
add_action('wp_ajax_aicc_writing_assist', [$this, 'handle_ajax_request']);
}
public function add_tinymce_buttons($buttons) {
array_push($buttons, 'aicc_assistant');
return $buttons;
}
public function add_tinymce_plugins($plugins) {
$plugins['aicc_assistant'] = AICC_PLUGIN_URL . 'assets/js/tinymce-plugin.js';
return $plugins;
}
public function register_gutenberg_blocks() {
register_block_type('aicc/writing-assistant', [
'editor_script' => 'aicc-gutenberg-blocks',
'render_callback' => [$this, 'render_writing_assistant_block']
]);
}
public function handle_ajax_request() {
check_ajax_referer('aicc_writing_assist_nonce', 'nonce');
$action = sanitize_text_field($_POST['action_type']);
$content = wp_kses_post($_POST['content']);
$options = isset($_POST['options']) ? $_POST['options'] : [];
switch ($action) {
case 'expand_idea':
$result = $this->expand_idea($content, $options);
break;
case 'improve_sentence':
$result = $this->improve_sentence($content, $options);
break;
case 'generate_headline':
$result = $this->generate_headline($content, $options);
break;
case 'check_grammar':
$result = $this->check_grammar($content);
break;
default:
$result = new WP_Error('invalid_action', '无效的操作类型');
}
if (is_wp_error($result)) {
wp_send_json_error($result->get_error_message());
} else {
wp_send_json_success($result);
}
}
public function expand_idea($idea, $options = []) {
$prompt = "请扩展以下想法,形成完整的段落:nn{$idea}";
if (!empty($options['tone'])) {
$prompt .= "nn使用{$options['tone']}的语气。";
}
return AI_Service_Manager::generate_content($prompt, [
'max_tokens' => 500,
'temperature' => 0.7
]);
}
public function improve_sentence($sentence, $options = []) {
$improvement_type = $options['type'] ?? 'clarity';
$instructions = [
'clarity' => '提高清晰度和可读性',
'conciseness' => '使表达更简洁',
'formality' => '使语气更正式',
'creativity' => '增加创意和表现力'
];
$instruction = isset($instructions[$improvement_type]) ?
$instructions[$improvement_type] :
'改进句子';
$prompt = "请{$instruction}:nn{$sentence}nn提供3个改进版本。";
3.3 内容优化与SEO增强功能
class SEO_Analyzer {
public function analyze_content($content, $focus_keyword = '') {
$analysis = [
'score' => 0,
'checks' => [],
'suggestions' => []
];
// 基础分析
$analysis['checks']['word_count'] = $this->check_word_count($content);
$analysis['checks']['headings'] = $this->check_headings($content);
$analysis['checks']['paragraph_length'] = $this->check_paragraph_length($content);
$analysis['checks']['link_count'] = $this->check_link_count($content);
// SEO特定分析
if (!empty($focus_keyword)) {
$analysis['checks']['keyword_density'] = $this->check_keyword_density($content, $focus_keyword);
$analysis['checks']['keyword_in_title'] = $this->check_keyword_in_title($content, $focus_keyword);
$analysis['checks']['keyword_in_meta'] = $this->check_keyword_in_meta($content, $focus_keyword);
$analysis['checks']['keyword_in_first_paragraph'] = $this->check_keyword_in_first_paragraph($content, $focus_keyword);
}
// 可读性分析
$analysis['checks']['readability'] = $this->check_readability($content);
// 计算总分
$analysis['score'] = $this->calculate_total_score($analysis['checks']);
// 生成建议
$analysis['suggestions'] = $this->generate_suggestions($analysis['checks']);
return $analysis;
}
private function check_word_count($content) {
$word_count = str_word_count(strip_tags($content));
$result = [
'passed' => false,
'value' => $word_count,
'message' => ''
];
if ($word_count >= 300) {
$result['passed'] = true;
$result['message'] = "文章长度合适({$word_count}字)";
} else {
$result['message'] = "文章可能过短({$word_count}字),建议至少300字";
}
return $result;
}
private function check_keyword_density($content, $keyword) {
$clean_content = strip_tags(strtolower($content));
$keyword_lower = strtolower($keyword);
$total_words = str_word_count($clean_content);
$keyword_count = substr_count($clean_content, $keyword_lower);
$density = $total_words > 0 ? ($keyword_count / $total_words) * 100 : 0;
$result = [
'passed' => false,
'value' => round($density, 2),
'message' => ''
];
if ($density >= 0.5 && $density <= 2.5) {
$result['passed'] = true;
$result['message'] = "关键词密度合适({$result['value']}%)";
} elseif ($density < 0.5) {
$result['message'] = "关键词密度偏低({$result['value']}%),建议适当增加";
} else {
$result['message'] = "关键词密度偏高({$result['value']}%),可能被判定为关键词堆砌";
}
return $result;
}
public function generate_seo_title($content, $keyword = '') {
$prompt = "为以下内容生成一个SEO友好的标题";
if (!empty($keyword)) {
$prompt .= ",需要包含关键词'{$keyword}'";
}
$prompt .= ":nn" . substr(strip_tags($content), 0, 500);
$titles = AI_Service_Manager::generate_content($prompt, [
'max_tokens' => 200,
'temperature' => 0.7
]);
if (is_wp_error($titles)) {
return $titles;
}
return $this->extract_titles_from_response($titles);
}
public function generate_meta_description($content, $keyword = '') {
$prompt = "为以下内容生成一个吸引点击的meta描述(150-160字符)";
if (!empty($keyword)) {
$prompt .= ",自然地包含关键词'{$keyword}'";
}
$prompt .= ":nn" . substr(strip_tags($content), 0, 300);
$description = AI_Service_Manager::generate_content($prompt, [
'max_tokens' => 100,
'temperature' => 0.6
]);
if (is_wp_error($description)) {
return $description;
}
// 清理和截断描述
$clean_description = preg_replace('/s+/', ' ', strip_tags($description));
return substr($clean_description, 0, 160);
}
public function suggest_lsi_keywords($content, $main_keyword) {
$prompt = "基于以下内容和主关键词'{$main_keyword}',生成5个相关的LSI(潜在语义索引)关键词:nn" .
substr(strip_tags($content), 0, 1000);
$keywords = AI_Service_Manager::generate_content($prompt, [
'max_tokens' => 150,
'temperature' => 0.5
]);
if (is_wp_error($keywords)) {
return $keywords;
}
return $this->extract_keywords_from_response($keywords);
}
}
第四部分:常用互联网小工具集成
4.1 多功能工具管理器
class Tools_Manager {
private $tools = [];
public function __construct() {
$this->register_default_tools();
add_action('init', [$this, 'init_tools']);
}
private function register_default_tools() {
$this->register_tool('seo_analyzer', [
'name' => 'SEO分析工具',
'description' => '分析内容SEO表现并提供优化建议',
'class' => 'SEO_Analyzer',
'ajax_action' => 'aicc_analyze_seo'
]);
$this->register_tool('readability_checker', [
'name' => '可读性检查',
'description' => '检查内容可读性水平',
'class' => 'Readability_Checker',
'ajax_action' => 'aicc_check_readability'
]);
$this->register_tool('plagiarism_checker', [
'name' => '原创性检查',
'description' => '检查内容原创性',
'class' => 'Plagiarism_Checker',
'ajax_action' => 'aicc_check_plagiarism'
]);
$this->register_tool('text_summarizer', [
'name' => '文本摘要',
'description' => '自动生成内容摘要',
'class' => 'Text_Summarizer',
'ajax_action' => 'aicc_summarize_text'
]);
$this->register_tool('image_alt_generator', [
'name' => '图片ALT文本生成',
'description' => '为图片生成SEO友好的ALT文本',
'class' => 'Image_Alt_Generator',
'ajax_action' => 'aicc_generate_alt_text'
]);
}
public function register_tool($tool_id, $config) {
$this->tools[$tool_id] = wp_parse_args($config, [
'name' => $tool_id,
'description' => '',
'class' => '',
'ajax_action' => '',
'enabled' => true,
'settings' => []
]);
}
public function init_tools() {
foreach ($this->tools as $tool_id => $tool) {
if ($tool['enabled'] && !empty($tool['ajax_action'])) {
add_action("wp_ajax_{$tool['ajax_action']}", [$this, "handle_{$tool_id}_request"]);
if (!empty($tool['class']) && class_exists($tool['class'])) {
$this->tools[$tool_id]['instance'] = new $tool['class']();
}
}
}
// 注册短代码
$this->register_tool_shortcodes();
}
public function register_tool_shortcodes() {
add_shortcode('aicc_tool', [$this, 'render_tool_shortcode']);
add_shortcode('aicc_seo_analyzer', [$this, 'render_seo_analyzer']);
add_shortcode('aicc_readability_check', [$this, 'render_readability_checker']);
add_shortcode('aicc_text_summarizer', [$this, 'render_text_summarizer']);
}
public function render_tool_shortcode($atts) {
$atts = shortcode_atts([
'tool' => 'seo_analyzer',
'title' => '',
'width' => '100%',
'height' => '400px'
], $atts);
$tool_id = sanitize_text_field($atts['tool']);
if (!isset($this->tools[$tool_id]) || !$this->tools[$tool_id]['enabled']) {
return '<p>工具不可用</p>';
}
ob_start();
?>
<div class="aicc-tool-container" data-tool="<?php echo esc_attr($tool_id); ?>">
<?php if (!empty($atts['title'])): ?>
<h3><?php echo esc_html($atts['title']); ?></h3>
<?php endif; ?>
<div class="aicc-tool-content">
<?php $this->render_tool_interface($tool_id); ?>
</div>
</div>
<style>
.aicc-tool-container {
width: <?php echo esc_attr($atts['width']); ?>;
height: <?php echo esc_attr($atts['height']); ?>;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
margin: 20px 0;
background: #f9f9f9;
}
</style>
<?php
return ob_get_clean();
}
private function render_tool_interface($tool_id) {
switch ($tool_id) {
case 'seo_analyzer':
$this->render_seo_analyzer_interface();
break;
case 'readability_checker':
$this->render_readability_checker_interface();
break;
case 'text_summarizer':
$this->render_text_summarizer_interface();
break;
default:
echo '<p>该工具界面正在开发中</p>';
}
}
private function render_seo_analyzer_interface() {
?>
<div class="aicc-seo-analyzer">
<textarea id="aicc-seo-content" placeholder="请输入要分析的内容..." rows="8" style="width:100%;"></textarea>
<input type="text" id="aicc-seo-keyword" placeholder="主关键词(可选)" style="width:100%; margin:10px 0; padding:8px;">
<div style="margin:15px 0;">
<label>
<input type="checkbox" id="aicc-check-readability" checked> 检查可读性
</label>
<label style="margin-left:15px;">
<input type="checkbox" id="aicc-check-structure" checked> 检查结构
</label>
</div>
<button id="aicc-analyze-seo-btn" class="button button-primary">分析SEO</button>
<div id="aicc-seo-results" style="margin-top:20px; display:none;">
<div class="aicc-score-circle" style="width:100px; height:100px; border-radius:50%; border:5px solid #ddd; display:flex; align-items:center; justify-content:center; margin:0 auto;">
<span id="aicc-seo-score" style="font-size:24px; font-weight:bold;">0</span>
</div>
<div id="aicc-seo-checks" style="margin-top:20px;"></div>
<div id="aicc-seo-suggestions" style="margin-top:20px; padding:15px; background:#fff; border-radius:5px;"></div>
</div>
</div>
<script>
jQuery(document).ready(function($) {
$('#aicc-analyze-seo-btn').on('click', function() {
var content = $('#aicc-seo-content').val();
var keyword = $('#aicc-seo-keyword').val();
if (!content.trim()) {
alert('请输入要分析的内容');
return;
}
$(this).prop('disabled', true).text('分析中...');
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: {
action: 'aicc_analyze_seo',
content: content,
keyword: keyword,
nonce: '<?php echo wp_create_nonce("aicc_seo_analysis"); ?>'
},
success: function(response) {
if (response.success) {
var data = response.data;
$('#aicc-seo-score').text(data.score);
$('#aicc-seo-results').show();
// 更新检查结果
var checksHtml = '<h4>检查结果:</h4><ul>';
for (var check in data.checks) {
var checkData = data.checks[check];
var statusIcon = checkData.passed ? '✅' : '❌';
checksHtml += '<li>' + statusIcon + ' ' + checkData.message + '</li>';
}
checksHtml += '</ul>';
$('#aicc-seo-checks').html(checksHtml);
// 更新建议
if (data.suggestions && data.suggestions.length > 0) {
var suggestionsHtml = '<h4>优化建议:</h4><ul>';
data.suggestions.forEach(function(suggestion) {
suggestionsHtml += '<li>💡 ' + suggestion + '</li>';
});
suggestionsHtml += '</ul>';
$('#aicc-seo-suggestions').html(suggestionsHtml);
}
// 更新分数圆环颜色
var scoreCircle = $('.aicc-score-circle');
var score = parseInt(data.score);
var color;
if (score >= 80) color = '#4CAF50';
else if (score >= 60) color = '#FFC107';
else color = '#F44336';
scoreCircle.css('border-color', color);
} else {
alert('分析失败:' + response.data);
}
},
error: function() {
alert('请求失败,请重试');
},
complete: function() {
$('#aicc-analyze-seo-btn').prop('disabled', false).text('分析SEO');
}
});
});
});
</script>
<?php
}
}
4.2 实用小工具集合实现
class Text_Summarizer {
public function summarize($text, $options = []) {
$default_options = [
'length' => 'medium', // short, medium, long
'format' => 'paragraph', // paragraph, bullet_points
'focus' => 'main_points' // main_points, key_facts, conclusions
];
$options = wp_parse_args($options, $default_options);
$length_instructions = [
'short' => '生成一个非常简短的摘要(约50字)',
'medium' => '生成一个中等长度的摘要(约100-150字)',
'long' => '生成一个详细的摘要(约200-300字)'
];
$format_instructions = [
'paragraph' => '以段落形式呈现',
'bullet_points' => '以要点列表形式呈现'
];
$focus_instructions = [
'main_points' => '重点关注主要观点',
'key_facts' => '重点关注关键事实和数据',
'conclusions' => '重点关注结论和建议'
];
$instruction = $length_instructions[$options['length']] . ',' .
$format_instructions[$options['format']] . ',' .
$focus_instructions[$options['focus']];
$prompt = "请为以下文本{$instruction}:nn{$text}";
return AI_Service_Manager::generate_content($prompt, [
'max_tokens' => $this->get_token_limit($options['length']),
'temperature' => 0.5
]);
}
public function generate_tldr($text) {
$prompt = "为以下文本生成一个'太长不看版'(TL;DR)摘要,要求简洁明了:nn{$text}";
return AI_Service_Manager::generate_content($prompt, [
'max_tokens' => 100,
'temperature' => 0.4
]);
}
}
class Readability_Checker {
public function analyze($text) {
$analysis = [
'flesch_reading_ease' => $this->calculate_flesch_reading_ease($text),
'flesch_kincaid_grade' => $this->calculate_flesch_kincaid_grade($text),
'gunning_fog' => $this->calculate_gunning_fog_index($text),
'smog_index' => $this->calculate_smog_index($text),
'automated_readability' => $this->calculate_automated_readability($text),
'coleman_liau' => $this->calculate_coleman_liau_index($text)
];
$analysis['overall_level'] = $this->determine_readability_level($analysis);
