文章目录[隐藏]
一步步教你,在WordPress中添加网站内容词云与关键词分析工具
引言:为什么WordPress网站需要内容分析工具
在当今信息爆炸的时代,网站内容管理已不再是简单的发布与展示。对于WordPress网站管理员和内容创作者而言,深入了解网站内容结构、关键词分布和用户关注点变得至关重要。词云和关键词分析工具能够直观展示网站内容的核心主题,帮助优化内容策略,提升SEO效果,并增强用户体验。
传统的WordPress功能虽然强大,但在内容分析方面往往需要依赖第三方插件,这些插件可能存在兼容性问题、性能负担或功能限制。通过代码二次开发实现自定义的词云与关键词分析工具,不仅能完全控制功能特性,还能确保与网站主题完美融合,提升整体性能。
本文将详细指导您如何通过WordPress代码二次开发,为您的网站添加专业级的内容词云与关键词分析功能。无论您是WordPress开发者还是有一定技术基础的管理员,都能跟随本文步骤实现这一实用功能。
第一部分:准备工作与环境搭建
1.1 开发环境要求
在开始开发之前,请确保您的环境满足以下要求:
- WordPress 5.0及以上版本
- PHP 7.2及以上版本(推荐PHP 7.4+)
- 基本的HTML、CSS、JavaScript知识
- 对WordPress主题结构和插件开发有基本了解
- 代码编辑器(如VS Code、Sublime Text等)
- 本地或测试服务器环境
1.2 创建开发环境
为了避免影响生产网站,建议在本地或测试服务器上进行开发:
-
本地开发环境设置:
- 使用Local by Flywheel、XAMPP或MAMP搭建本地WordPress环境
- 安装一个干净的WordPress实例
- 选择并激活一个基础主题(如Twenty Twenty-One)
-
创建子主题:
如果您计划修改现有主题,强烈建议创建子主题:/* Theme Name: My Custom Theme Child Template: twentytwentyone */将上述代码保存为style.css,放在新创建的子主题文件夹中。
-
启用调试模式:
在wp-config.php中添加以下代码,以便在开发过程中查看错误信息:define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); define('WP_DEBUG_DISPLAY', false);
1.3 工具与库准备
我们将使用以下开源库来构建词云和关键词分析功能:
- WordCloud.js:一个基于HTML5 Canvas的JavaScript词云库
- Chart.js:用于创建关键词分析图表
- 自然语言处理工具:我们将使用PHP的文本处理功能,对于更高级的分析,可以考虑集成PHP-ML库
下载这些库文件,或通过CDN链接在项目中引用。
第二部分:词云功能设计与实现
2.1 词云功能设计思路
词云功能的核心是从网站内容中提取关键词,并根据词频生成可视化云图。我们的设计将包括以下组件:
- 数据收集模块:从文章、页面等内容中提取文本
- 文本处理模块:清洗文本,去除停用词,提取关键词
- 词频统计模块:计算每个关键词的出现频率
- 可视化模块:将词频数据转换为可视化词云
- 显示控制模块:提供配置选项,控制词云的显示方式
2.2 创建词云插件基础结构
我们将创建一个独立的WordPress插件来实现词云功能:
-
创建插件文件夹和主文件:
在wp-content/plugins目录下创建"wordpress-content-analyzer"文件夹,并在其中创建主插件文件:<?php /** * Plugin Name: WordPress内容分析器 * Plugin URI: https://yourwebsite.com/ * Description: 为WordPress网站添加词云和关键词分析功能 * Version: 1.0.0 * Author: 您的名称 * License: GPL v2 or later */ // 防止直接访问 if (!defined('ABSPATH')) { exit; } // 定义插件常量 define('WCA_PLUGIN_DIR', plugin_dir_path(__FILE__)); define('WCA_PLUGIN_URL', plugin_dir_url(__FILE__)); define('WCA_VERSION', '1.0.0'); // 初始化插件 function wca_initialize_plugin() { // 检查WordPress版本 if (version_compare(get_bloginfo('version'), '5.0', '<')) { deactivate_plugins(basename(__FILE__)); wp_die(__('本插件需要WordPress 5.0或更高版本。', 'wordpress-content-analyzer')); } // 加载必要文件 require_once WCA_PLUGIN_DIR . 'includes/class-text-processor.php'; require_once WCA_PLUGIN_DIR . 'includes/class-word-cloud.php'; require_once WCA_PLUGIN_DIR . 'includes/class-keyword-analyzer.php'; } add_action('plugins_loaded', 'wca_initialize_plugin');
2.3 文本处理与关键词提取
创建文本处理类,用于从WordPress内容中提取和清洗关键词:
<?php
// includes/class-text-processor.php
class WCA_Text_Processor {
private $stop_words;
public function __construct() {
// 中文停用词列表(简化版,实际应用中需要更完整的列表)
$this->stop_words = array(
'的', '了', '在', '是', '我', '有', '和', '就',
'不', '人', '都', '一', '一个', '上', '也', '很',
'到', '说', '要', '去', '你', '会', '着', '没有',
'看', '好', '自己', '这', '那', '他', '她', '它'
);
// 可以添加英文停用词
$english_stop_words = array(
'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on',
'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are',
'was', 'were', 'be', 'been', 'being', 'have', 'has',
'had', 'having', 'do', 'does', 'did', 'doing'
);
$this->stop_words = array_merge($this->stop_words, $english_stop_words);
}
/**
* 从文章内容中提取文本
*/
public function extract_text_from_post($post_id) {
$post = get_post($post_id);
if (!$post) {
return '';
}
// 提取标题和内容
$text = $post->post_title . ' ' . $post->post_content;
// 移除HTML标签
$text = wp_strip_all_tags($text);
// 移除短代码
$text = strip_shortcodes($text);
return $text;
}
/**
* 从多个文章中提取文本
*/
public function extract_text_from_posts($post_ids = array()) {
$all_text = '';
if (empty($post_ids)) {
// 获取所有已发布的文章
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids'
);
$post_ids = get_posts($args);
}
foreach ($post_ids as $post_id) {
$all_text .= $this->extract_text_from_post($post_id) . ' ';
}
return $all_text;
}
/**
* 清洗文本并提取关键词
*/
public function process_text($text, $max_words = 100) {
// 转换为小写(针对英文)
$text = mb_strtolower($text, 'UTF-8');
// 移除标点符号和数字
$text = preg_replace('/[[:punct:]]/u', ' ', $text);
$text = preg_replace('/[0-9]+/', ' ', $text);
// 分割为单词/词语
// 这里使用简单空格分割,中文需要更复杂的分词处理
$words = preg_split('/s+/', $text);
// 移除空值和停用词
$words = array_filter($words, function($word) {
return !empty($word) && !in_array($word, $this->stop_words) && mb_strlen($word, 'UTF-8') > 1;
});
// 统计词频
$word_counts = array_count_values($words);
// 按词频排序
arsort($word_counts);
// 限制返回的词数
$word_counts = array_slice($word_counts, 0, $max_words, true);
return $word_counts;
}
/**
* 改进的中文分词方法(简单实现)
*/
public function chinese_segmentation($text) {
// 这是一个简化的中文分词方法
// 实际应用中建议使用更专业的分词库,如jieba-php
// 将文本按常见分隔符分割
$delimiters = array(',', '。', '!', '?', ';', '、', ' ', ',', '.', '!', '?', ';');
$text = str_replace($delimiters, ' ', $text);
// 简单按字符分割(对于中文,这只是一个基础实现)
// 更好的方法是使用字典匹配或机器学习分词
$words = array();
$length = mb_strlen($text, 'UTF-8');
for ($i = 0; $i < $length; $i++) {
// 获取单个字符
$char = mb_substr($text, $i, 1, 'UTF-8');
// 如果是中文,尝试获取2-4个字符的词语
if (preg_match('/[x{4e00}-x{9fa5}]/u', $char)) {
// 添加单字
$words[] = $char;
// 尝试添加双字词
if ($i + 1 < $length) {
$two_char = mb_substr($text, $i, 2, 'UTF-8');
if (preg_match('/^[x{4e00}-x{9fa5}]{2}$/u', $two_char)) {
$words[] = $two_char;
}
}
// 尝试添加三字词
if ($i + 2 < $length) {
$three_char = mb_substr($text, $i, 3, 'UTF-8');
if (preg_match('/^[x{4e00}-x{9fa5}]{3}$/u', $three_char)) {
$words[] = $three_char;
}
}
} else {
// 非中文字符,按空格分割的单词处理
if ($i > 0 && mb_substr($text, $i-1, 1, 'UTF-8') !== ' ') {
continue;
}
// 提取英文单词
$j = $i;
while ($j < $length && preg_match('/[a-z]/i', mb_substr($text, $j, 1, 'UTF-8'))) {
$j++;
}
if ($j > $i) {
$word = mb_substr($text, $i, $j-$i, 'UTF-8');
$words[] = $word;
$i = $j - 1;
}
}
}
return $words;
}
}
2.4 词云可视化实现
创建词云类,用于生成词云数据并渲染可视化:
<?php
// includes/class-word-cloud.php
class WCA_Word_Cloud {
private $text_processor;
public function __construct() {
$this->text_processor = new WCA_Text_Processor();
// 注册短代码
add_shortcode('wordcloud', array($this, 'wordcloud_shortcode'));
// 注册小工具
add_action('widgets_init', array($this, 'register_widget'));
// 添加管理页面
add_action('admin_menu', array($this, 'add_admin_menu'));
}
/**
* 生成词云数据
*/
public function generate_wordcloud_data($post_ids = array(), $max_words = 50) {
// 提取文本
$text = $this->text_processor->extract_text_from_posts($post_ids);
// 处理文本并获取词频
$word_counts = $this->text_processor->process_text($text, $max_words);
// 格式化数据供JavaScript使用
$wordcloud_data = array();
foreach ($word_counts as $word => $count) {
$wordcloud_data[] = array(
'text' => $word,
'size' => $count * 10, // 根据词频调整大小
'count' => $count
);
}
return $wordcloud_data;
}
/**
* 渲染词云HTML
*/
public function render_wordcloud($post_ids = array(), $max_words = 50, $width = 800, $height = 600) {
// 获取词云数据
$wordcloud_data = $this->generate_wordcloud_data($post_ids, $max_words);
// 生成唯一ID
$cloud_id = 'wordcloud-' . uniqid();
// 输出HTML结构
$output = '<div class="wordcloud-container">';
$output .= '<div id="' . $cloud_id . '" class="wordcloud-canvas" style="width: ' . $width . 'px; height: ' . $height . 'px;"></div>';
$output .= '<div class="wordcloud-legend"></div>';
$output .= '</div>';
// 添加JavaScript代码
$output .= '<script type="text/javascript">';
$output .= 'jQuery(document).ready(function($) {';
$output .= 'var wordcloudData = ' . json_encode($wordcloud_data) . ';';
$output .= 'WCA_WordCloud.render("#' . $cloud_id . '", wordcloudData);';
$output .= '});';
$output .= '</script>';
return $output;
}
/**
* 短代码处理函数
*/
public function wordcloud_shortcode($atts) {
// 解析短代码属性
$atts = shortcode_atts(array(
'max_words' => 50,
'width' => 800,
'height' => 600,
'post_ids' => ''
), $atts, 'wordcloud');
// 处理post_ids参数
$post_ids = array();
if (!empty($atts['post_ids'])) {
$post_ids = array_map('intval', explode(',', $atts['post_ids']));
}
// 渲染词云
return $this->render_wordcloud(
$post_ids,
intval($atts['max_words']),
intval($atts['width']),
intval($atts['height'])
);
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_options_page(
'词云设置',
'内容词云',
'manage_options',
'wordcloud-settings',
array($this, 'render_admin_page')
);
}
/**
* 渲染管理页面
*/
public function render_admin_page() {
?>
<div class="wrap">
<h1>词云设置</h1>
<form method="post" action="options.php">
<?php
settings_fields('wordcloud_settings');
do_settings_sections('wordcloud_settings');
?>
<table class="form-table">
<tr>
<th scope="row">默认显示词数</th>
<td>
<input type="number" name="wordcloud_max_words" value="<?php echo esc_attr(get_option('wordcloud_max_words', 50)); ?>" min="10" max="200">
<p class="description">词云中默认显示的关键词数量</p>
</td>
</tr>
<tr>
<th scope="row">排除词语</th>
<td>
<textarea name="wordcloud_exclude_words" rows="5" cols="50"><?php echo esc_textarea(get_option('wordcloud_exclude_words', '')); ?></textarea>
<p class="description">每行一个,这些词语不会出现在词云中</p>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
<h2>预览</h2>
<div id="wordcloud-preview">
<?php echo $this->render_wordcloud(); ?>
</div>
</div>
<?php
}
/**
* 注册小工具
*/
public function register_widget() {
register_widget('WCA_WordCloud_Widget');
}
}
// 词云小工具类
class WCA_WordCloud_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'wca_wordcloud_widget',
'内容词云',
array('description' => '显示网站内容词云')
);
}
public function widget($args, $instance) {
echo $args['before_widget'];
if (!empty($instance['title'])) {
echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
}
$max_words = !empty($instance['max_words']) ? $instance['max_words'] : 30;
instance['width'] : 300;
$height = !empty($instance['height']) ? $instance['height'] : 300;
$wordcloud = new WCA_Word_Cloud();
echo $wordcloud->render_wordcloud(array(), $max_words, $width, $height);
echo $args['after_widget'];
}
public function form($instance) {
$title = !empty($instance['title']) ? $instance['title'] : '内容词云';
$max_words = !empty($instance['max_words']) ? $instance['max_words'] : 30;
$width = !empty($instance['width']) ? $instance['width'] : 300;
$height = !empty($instance['height']) ? $instance['height'] : 300;
?>
<p>
<label for="<?php echo esc_attr($this->get_field_id('title')); ?>">标题:</label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>"
name="<?php echo esc_attr($this->get_field_name('title')); ?>"
type="text" value="<?php echo esc_attr($title); ?>">
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('max_words')); ?>">显示词数:</label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('max_words')); ?>"
name="<?php echo esc_attr($this->get_field_name('max_words')); ?>"
type="number" value="<?php echo esc_attr($max_words); ?>" min="10" max="100">
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('width')); ?>">宽度:</label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('width')); ?>"
name="<?php echo esc_attr($this->get_field_name('width')); ?>"
type="number" value="<?php echo esc_attr($width); ?>" min="200" max="1000">
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('height')); ?>">高度:</label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('height')); ?>"
name="<?php echo esc_attr($this->get_field_name('height')); ?>"
type="number" value="<?php echo esc_attr($height); ?>" min="200" max="1000">
</p>
<?php
}
public function update($new_instance, $old_instance) {
$instance = array();
$instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
$instance['max_words'] = (!empty($new_instance['max_words'])) ? intval($new_instance['max_words']) : 30;
$instance['width'] = (!empty($new_instance['width'])) ? intval($new_instance['width']) : 300;
$instance['height'] = (!empty($new_instance['height'])) ? intval($new_instance['height']) : 300;
return $instance;
}
}
### 2.5 前端JavaScript实现
创建前端JavaScript文件,用于渲染词云可视化:
// assets/js/wordcloud-renderer.js
var WCA_WordCloud = (function() {
// 私有变量
var defaultColors = [
'#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'
];
// 渲染词云
function render(containerSelector, wordData) {
var container = document.querySelector(containerSelector);
if (!container) {
console.error('词云容器未找到: ' + containerSelector);
return;
}
// 清空容器
container.innerHTML = '';
// 计算最大和最小词频
var maxSize = Math.max.apply(Math, wordData.map(function(item) { return item.size; }));
var minSize = Math.min.apply(Math, wordData.map(function(item) { return item.size; }));
// 创建词云元素
wordData.forEach(function(wordObj, index) {
var wordElement = document.createElement('span');
wordElement.className = 'cloud-word';
wordElement.textContent = wordObj.text;
// 计算字体大小(基于词频)
var fontSize = 14 + (wordObj.size - minSize) / (maxSize - minSize) * 36;
wordElement.style.fontSize = fontSize + 'px';
// 设置随机颜色
var colorIndex = index % defaultColors.length;
wordElement.style.color = defaultColors[colorIndex];
// 设置透明度
var opacity = 0.7 + (wordObj.size - minSize) / (maxSize - minSize) * 0.3;
wordElement.style.opacity = opacity;
// 设置鼠标悬停效果
wordElement.style.cursor = 'pointer';
wordElement.style.display = 'inline-block';
wordElement.style.margin = '5px';
wordElement.style.padding = '2px 5px';
wordElement.style.transition = 'all 0.3s ease';
wordElement.addEventListener('mouseover', function() {
this.style.transform = 'scale(1.2)';
this.style.zIndex = '100';
this.style.backgroundColor = 'rgba(0,0,0,0.1)';
this.style.borderRadius = '3px';
});
wordElement.addEventListener('mouseout', function() {
this.style.transform = 'scale(1)';
this.style.zIndex = '1';
this.style.backgroundColor = 'transparent';
});
// 点击事件:显示词频
wordElement.addEventListener('click', function() {
alert('关键词: ' + wordObj.text + 'n出现次数: ' + wordObj.count);
});
container.appendChild(wordElement);
});
// 添加CSS样式
addCloudStyles();
}
// 添加词云样式
function addCloudStyles() {
if (document.getElementById('wordcloud-styles')) {
return;
}
var styleElement = document.createElement('style');
styleElement.id = 'wordcloud-styles';
styleElement.textContent = `
.wordcloud-container {
text-align: center;
padding: 20px;
background: #f9f9f9;
border-radius: 8px;
margin: 20px 0;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.wordcloud-canvas {
margin: 0 auto;
line-height: 1.5;
position: relative;
overflow: hidden;
}
.cloud-word {
display: inline-block;
margin: 5px;
padding: 2px 5px;
transition: all 0.3s ease;
font-family: 'Microsoft YaHei', sans-serif;
}
.cloud-word:hover {
transform: scale(1.2);
z-index: 100;
}
.wordcloud-legend {
margin-top: 20px;
font-size: 12px;
color: #666;
}
`;
document.head.appendChild(styleElement);
}
// 公共API
return {
render: render,
updateColors: function(colors) {
defaultColors = colors;
}
};
})();
## 第三部分:关键词分析工具实现
### 3.1 关键词分析功能设计
关键词分析工具将提供以下功能:
1. **词频统计**:显示关键词出现频率
2. **趋势分析**:展示关键词随时间的变化
3. **相关性分析**:分析关键词之间的关联
4. **SEO建议**:基于关键词分析提供优化建议
### 3.2 创建关键词分析类
<?php
// includes/class-keyword-analyzer.php
class WCA_Keyword_Analyzer {
private $text_processor;
public function __construct() {
$this->text_processor = new WCA_Text_Processor();
// 注册短代码
add_shortcode('keyword_analysis', array($this, 'keyword_analysis_shortcode'));
// 添加REST API端点
add_action('rest_api_init', array($this, 'register_rest_routes'));
}
/**
* 获取关键词统计数据
*/
public function get_keyword_stats($time_range = 'all', $limit = 20) {
global $wpdb;
// 根据时间范围确定日期条件
$date_condition = '';
if ($time_range !== 'all') {
$date = date('Y-m-d', strtotime('-' . $time_range));
$date_condition = " AND post_date >= '{$date}'";
}
// 获取文章内容
$query = "
SELECT ID, post_title, post_content, post_date
FROM {$wpdb->posts}
WHERE post_type = 'post'
AND post_status = 'publish'
{$date_condition}
ORDER BY post_date DESC
";
$posts = $wpdb->get_results($query);
// 提取所有文本
$all_text = '';
$posts_by_month = array();
foreach ($posts as $post) {
$text = $post->post_title . ' ' . $post->post_content;
$text = wp_strip_all_tags($text);
$text = strip_shortcodes($text);
$all_text .= $text . ' ';
// 按月份分组
$month = date('Y-m', strtotime($post->post_date));
if (!isset($posts_by_month[$month])) {
$posts_by_month[$month] = '';
}
$posts_by_month[$month] .= $text . ' ';
}
// 处理文本获取关键词
$all_keywords = $this->text_processor->process_text($all_text, $limit * 2);
// 获取每个关键词的月度趋势
$monthly_trends = array();
$top_keywords = array_slice($all_keywords, 0, $limit, true);
foreach (array_keys($top_keywords) as $keyword) {
$monthly_trends[$keyword] = array();
foreach ($posts_by_month as $month => $month_text) {
// 统计该关键词在当月出现的次数
$month_word_counts = $this->text_processor->process_text($month_text, 100);
$monthly_trends[$keyword][$month] = isset($month_word_counts[$keyword]) ? $month_word_counts[$keyword] : 0;
}
}
// 计算关键词相关性(简化版)
$correlations = $this->calculate_correlations($top_keywords, $posts);
return array(
'top_keywords' => $top_keywords,
'monthly_trends' => $monthly_trends,
'correlations' => $correlations,
'total_posts' => count($posts),
'time_range' => $time_range
);
}
/**
* 计算关键词相关性
*/
private function calculate_correlations($keywords, $posts) {
$correlations = array();
$keyword_list = array_keys($keywords);
// 初始化相关性矩阵
foreach ($keyword_list as $keyword1) {
foreach ($keyword_list as $keyword2) {
if ($keyword1 !== $keyword2) {
$correlations[$keyword1][$keyword2] = 0;
}
}
}
// 统计共同出现次数
foreach ($posts as $post) {
$text = $post->post_title . ' ' . $post->post_content;
$text = wp_strip_all_tags($text);
$text = mb_strtolower($text, 'UTF-8');
foreach ($keyword_list as $keyword1) {
if (strpos($text, $keyword1) !== false) {
foreach ($keyword_list as $keyword2) {
if ($keyword1 !== $keyword2 && strpos($text, $keyword2) !== false) {
$correlations[$keyword1][$keyword2]++;
}
}
}
}
}
return $correlations;
}
/**
* 生成SEO建议
*/
public function generate_seo_recommendations($keyword_stats) {
$recommendations = array();
$top_keywords = $keyword_stats['top_keywords'];
// 分析关键词密度
$total_words = array_sum($top_keywords);
foreach ($top_keywords as $keyword => $count) {
$density = ($count / $total_words) * 100;
if ($density < 1) {
$recommendations[] = sprintf(
'关键词"%s"的密度较低(%.2f%%),建议在相关文章中增加使用频率',
$keyword,
$density
);
} elseif ($density > 5) {
$recommendations[] = sprintf(
'关键词"%s"的密度较高(%.2f%%),注意避免关键词堆砌',
$keyword,
$density
);
}
}
// 检查长尾关键词
if (count($top_keywords) < 10) {
$recommendations[] = '网站关键词数量较少,建议增加内容多样性,覆盖更多长尾关键词';
}
// 基于相关性建议
$correlations = $keyword_stats['correlations'];
$high_correlations = array();
foreach ($correlations as $kw1 => $related) {
foreach ($related as $kw2 => $score) {
if ($score > 5 && !isset($high_correlations[$kw2 . '-' . $kw1])) {
$high_correlations[$kw1 . '-' . $kw2] = array(
'keywords' => array($kw1, $kw2),
'score' => $score
);
}
}
}
if (!empty($high_correlations)) {
$recommendations[] = '以下关键词经常同时出现,可以考虑创建相关内容:';
foreach ($high_correlations as $pair) {
$recommendations[] = sprintf(
'- "%s" 和 "%s" (共同出现%d次)',
$pair['keywords'][0],
$pair['keywords'][1],
$pair['score']
);
}
}
return $recommendations;
}
/**
* 渲染关键词分析报告
*/
public function render_analysis_report($time_range = 'all', $limit = 15) {
// 获取统计数据
$stats = $this->get_keyword_stats($time_range, $limit);
$recommendations = $this->generate_seo_recommendations($stats);
// 生成唯一ID
$report_id = 'keyword-analysis-' . uniqid();
// 输出HTML结构
$output = '<div class="keyword-analysis-report" id="' . $report_id . '">';
$output .= '<div class="report-header">';
$output .= '<h3>关键词分析报告</h3>';
$output .= '<p>分析时间范围: ' . $this->get_time_range_label($time_range) . ' | 分析文章: ' . $stats['total_posts'] . '篇</p>';
$output .= '</div>';
// 关键词排名表格
$output .= '<div class="keyword-ranking">';
$output .= '<h4>关键词排名TOP' . $limit . '</h4>';
$output .= '<table class="wp-list-table widefat fixed striped">';
$output .= '<thead><tr><th>排名</th><th>关键词</th><th>出现次数</th><th>占比</th><th>趋势</th></tr></thead>';
$output .= '<tbody>';
$total = array_sum($stats['top_keywords']);
$rank = 1;
foreach ($stats['top_keywords'] as $keyword => $count) {
$percentage = round(($count / $total) * 100, 2);
$trend = $this->get_trend_icon($stats['monthly_trends'][$keyword]);
$output .= '<tr>';
$output .= '<td>' . $rank . '</td>';
$output .= '<td><strong>' . esc_html($keyword) . '</strong></td>';
$output .= '<td>' . $count . '</td>';
$output .= '<td>' . $percentage . '%</td>';
$output .= '<td>' . $trend . '</td>';
$output .= '</tr>';
$rank++;
}
$output .= '</tbody></table></div>';
// 趋势图表容器
$output .= '<div class="trend-chart-container">';
$output .= '<h4>关键词趋势分析</h4>';
$output .= '<div class="chart-wrapper">';
$output .= '<canvas id="trend-chart-' . $report_id . '" width="800" height="400"></canvas>';
$output .= '</div>';
$output .= '</div>';
// SEO建议
$output .= '<div class="seo-recommendations">';
$output .= '<h4>SEO优化建议</h4>';
$output .= '<ul>';
foreach ($recommendations as $recommendation) {
$output .= '<li>' . esc_html($recommendation) . '</li>';
}
$output .= '</ul>';
$output .= '</div>';
$output .= '</div>';
// 添加JavaScript代码
$output .= $this->get
