文章目录[隐藏]
网络传媒柔性热点追踪与内容生成WordPress插件教程
概述:智能内容创作的新时代
在信息爆炸的今天,网络传媒工作者面临着巨大的挑战:如何快速追踪热点话题并生成高质量内容?传统的人工追踪方式效率低下,往往错过最佳发布时机。本教程将介绍一款专为WordPress设计的柔性热点追踪与内容生成插件,帮助您自动化这一过程,提升内容生产效率。
这款插件结合了网络爬虫、自然语言处理和智能内容生成技术,能够实时追踪多个平台的热点话题,并基于这些话题自动生成符合SEO标准的文章草稿,大大减轻了内容创作的压力。
插件安装与基础配置
1. 安装插件
首先,您需要将插件文件上传到WordPress的插件目录:
- 下载插件压缩包(例如:flexible-hotspot-tracker.zip)
- 登录WordPress后台,进入"插件" → "安装插件"
- 点击"上传插件",选择下载的压缩包
- 点击"立即安装",然后激活插件
2. 基础配置
激活插件后,您需要进行初始配置:
<?php
/**
* 插件基础配置示例代码
* 将此代码添加到主题的functions.php或自定义插件中
*/
// 定义热点追踪插件的配置
add_action('admin_init', 'fht_plugin_setup');
function fht_plugin_setup() {
// 注册插件设置
register_setting('fht_options_group', 'fht_api_key');
register_setting('fht_options_group', 'fht_tracking_sources');
register_setting('fht_options_group', 'fht_auto_publish');
// 设置默认值
$default_sources = array(
'weibo' => true,
'zhihu' => true,
'baidu_trend' => true,
'news_portals' => true
);
if (get_option('fht_tracking_sources') === false) {
update_option('fht_tracking_sources', $default_sources);
}
}
// 创建管理菜单
add_action('admin_menu', 'fht_create_menu');
function fht_create_menu() {
add_menu_page(
'柔性热点追踪设置', // 页面标题
'热点追踪', // 菜单标题
'manage_options', // 权限
'fht-settings', // 菜单slug
'fht_settings_page', // 回调函数
'dashicons-trending-up', // 图标
30 // 位置
);
}
?>
核心功能实现代码详解
1. 热点追踪模块
# hotspots_tracker.py
# 热点追踪核心模块
import requests
import json
import time
from datetime import datetime
from bs4 import BeautifulSoup
import mysql.connector
class HotspotTracker:
def __init__(self, config):
"""
初始化热点追踪器
:param config: 配置字典,包含API密钥、数据库设置等
"""
self.config = config
self.db_connection = self.connect_database()
self.sources = config.get('sources', [])
def connect_database(self):
"""连接WordPress数据库"""
try:
conn = mysql.connector.connect(
host=self.config['db_host'],
user=self.config['db_user'],
password=self.config['db_password'],
database=self.config['db_name']
)
return conn
except Exception as e:
print(f"数据库连接失败: {e}")
return None
def fetch_weibo_hotspots(self):
"""获取微博热搜榜"""
try:
url = "https://m.weibo.cn/api/container/getIndex?containerid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
data = response.json()
hotspots = []
for item in data['data']['cards'][0]['card_group']:
hotspot = {
'title': item['desc'],
'url': f"https://s.weibo.com/weibo?q={item['desc']}",
'heat': item.get('desc_extr', ''),
'source': 'weibo',
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
hotspots.append(hotspot)
return hotspots[:20] # 返回前20个热点
except Exception as e:
print(f"获取微博热点失败: {e}")
return []
def fetch_zhihu_hotspots(self):
"""获取知乎热榜"""
try:
url = "https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
data = response.json()
hotspots = []
for item in data['data']:
hotspot = {
'title': item['target']['title'],
'url': f"https://www.zhihu.com/question/{item['target']['id']}",
'heat': item['detail_text'],
'source': 'zhihu',
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
hotspots.append(hotspot)
return hotspots[:20]
except Exception as e:
print(f"获取知乎热点失败: {e}")
return []
def save_to_database(self, hotspots):
"""将热点保存到数据库"""
if not self.db_connection:
return False
cursor = self.db_connection.cursor()
for hotspot in hotspots:
sql = """
INSERT INTO wp_hotspots
(title, url, heat, source, created_at)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
heat = VALUES(heat), updated_at = NOW()
"""
values = (
hotspot['title'],
hotspot['url'],
hotspot['heat'],
hotspot['source'],
hotspot['timestamp']
)
cursor.execute(sql, values)
self.db_connection.commit()
cursor.close()
return True
def run_tracking(self):
"""执行热点追踪任务"""
all_hotspots = []
# 根据配置获取不同来源的热点
if 'weibo' in self.sources:
all_hotspots.extend(self.fetch_weibo_hotspots())
if 'zhihu' in self.sources:
all_hotspots.extend(self.fetch_zhihu_hotspots())
# 保存到数据库
if all_hotspots:
self.save_to_database(all_hotspots)
print(f"成功保存 {len(all_hotspots)} 个热点")
return all_hotspots
2. 内容生成模块
<?php
/**
* 内容生成器类
* 基于热点话题自动生成文章草稿
*/
class ContentGenerator {
private $openai_api_key;
private $wpdb;
public function __construct($api_key) {
$this->openai_api_key = $api_key;
global $wpdb;
$this->wpdb = $wpdb;
}
/**
* 从数据库获取最新热点
*/
public function get_latest_hotspots($limit = 5) {
$table_name = $this->wpdb->prefix . 'hotspots';
$query = $this->wpdb->prepare(
"SELECT * FROM {$table_name} ORDER BY created_at DESC LIMIT %d",
$limit
);
return $this->wpdb->get_results($query, ARRAY_A);
}
/**
* 使用AI生成文章内容
*/
public function generate_article($hotspot_title, $keywords = []) {
// 构建AI提示词
$prompt = "请以'{$hotspot_title}'为主题,撰写一篇800-1000字的网络媒体文章。nn";
$prompt .= "要求:n";
$prompt .= "1. 开头简要介绍热点事件n";
$prompt .= "2. 分析事件背景和原因n";
$prompt .= "3. 探讨社会影响和各方观点n";
$prompt .= "4. 提供客观的总结或展望n";
$prompt .= "5. 语言风格:专业但不失活泼,适合网络传播nn";
if (!empty($keywords)) {
$prompt .= "请自然融入以下关键词:" . implode('、', $keywords) . "n";
}
// 调用OpenAI API(示例)
$api_url = 'https://api.openai.com/v1/chat/completions';
$headers = [
'Authorization' => 'Bearer ' . $this->openai_api_key,
'Content-Type' => 'application/json'
];
$body = [
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => '你是一位专业的网络媒体编辑。'],
['role' => 'user', 'content' => $prompt]
],
'max_tokens' => 2000,
'temperature' => 0.7
];
// 实际使用中需要处理API响应
// $response = wp_remote_post($api_url, [
// 'headers' => $headers,
// 'body' => json_encode($body)
// ]);
// 这里返回模拟内容
$mock_content = $this->generate_mock_content($hotspot_title, $keywords);
return [
'title' => $hotspot_title . ':深度分析与展望',
'content' => $mock_content,
'excerpt' => wp_trim_words($mock_content, 50, '...'),
'status' => 'draft',
'tags' => $keywords
];
}
/**
* 生成模拟内容(实际使用中应调用AI API)
*/
private function generate_mock_content($title, $keywords) {
$content = "<h2>热点事件概述</h2>n";
$content .= "<p>近日,'{$title}'成为网络热议话题,引发广泛关注。这一现象不仅反映了当前社会的关注焦点,也揭示了更深层次的社会动态。</p>nn";
$content .= "<h2>背景与原因分析</h2>n";
$content .= "<p>要理解这一热点,我们需要从多个维度进行分析。首先,从社会背景来看...</p>n";
$content .= "<p>其次,技术发展也为这一现象提供了土壤...</p>nn";
$content .= "<h2>多方观点汇总</h2>n";
$content .= "<p>对于这一话题,各方观点不一:</p>n";
$content .= "<ul>n<li>支持者认为...</li>n<li>反对者指出...</li>n<li>中立专家建议...</li>n</ul>nn";
$content .= "<h2>影响与展望</h2>n";
$content .= "<p>这一热点事件可能带来以下影响:</p>n";
$content .= "<ol>n<li>短期影响...</li>n<li>中长期趋势...</li>n</ol>nn";
if (!empty($keywords)) {
$content .= "<p>关键词:" . implode('、', $keywords) . "</p>n";
}
$content .= "<p>本文由柔性热点追踪插件自动生成,编辑已进行审核修改。</p>";
return $content;
}
/**
* 创建WordPress文章
*/
public function create_post($article_data) {
$post_data = [
'post_title' => $article_data['title'],
'post_content' => $article_data['content'],
'post_excerpt' => $article_data['excerpt'],
'post_status' => $article_data['status'],
'post_author' => get_current_user_id(),
'post_type' => 'post',
'tags_input' => $article_data['tags']
];
$post_id = wp_insert_post($post_data);
if ($post_id && !is_wp_error($post_id)) {
// 添加自定义字段标记为AI生成
update_post_meta($post_id, '_fht_ai_generated', '1');
update_post_meta($post_id, '_fht_generated_time', current_time('mysql'));
return $post_id;
}
return false;
}
}
?>
插件高级功能与定制
1. 定时任务设置
<?php
/**
* 定时任务管理
* 设置自动追踪和内容生成计划
*/
// 创建自定义定时任务
add_filter('cron_schedules', 'fht_custom_cron_schedules');
function fht_custom_cron_schedules($schedules) {
$schedules['fht_hourly'] = [
'interval' => 3600, // 每小时
'display' => '每小时'
];
$schedules['fht_4hours'] = [
'interval' => 14400, // 每4小时
'display' => '每4小时'
];
return $schedules;
}
// 设置定时任务
register_activation_hook(__FILE__, 'fht_activate_cron');
function fht_activate_cron() {
if (!wp_next_scheduled('fht_hourly_hotspot_tracking')) {
wp_schedule_event(time(), 'fht_hourly', 'fht_hourly_hotspot_tracking');
}
if (!wp_next_scheduled('fht_daily_content_generation')) {
wp_schedule_event(time(), 'daily', 'fht_daily_content_generation');
}
}
// 热点追踪定时任务
add_action('fht_hourly_hotspot_tracking', 'fht_execute_hotspot_tracking');
function fht_execute_hotspot_tracking() {
$tracker = new HotspotTracker(get_option('fht_tracking_config'));
$hotspots = $tracker->run_tracking();
// 记录日志
fht_log_activity('热点追踪完成,发现' . count($hotspots) . '个新热点');
}
// 内容生成定时任务
add_action('fht_daily_content_generation', 'fht_execute_content_generation');
function fht_execute_content_generation() {
$api_key = get_option('fht_openai_api_key');
$generator = new ContentGenerator($api_key);
// 获取最新热点
$hotspots = $generator->get_latest_hotspots(3);
foreach ($hotspots as $hotspot) {
// 生成文章
$article = $generator->generate_article(
$hotspot['title'],
[$hotspot['source'], '热点追踪', '自动生成']
);
// 创建文章
$post_id = $generator->create_post($article);
if ($post_id) {
fht_log_activity('已生成文章:' . $article['title']);
}
}
}
?>
2. 前端展示小工具
<?php
/**
* 热点展示小工具
* 在网站侧边栏显示最新热点
*/
class Hotspot_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'hotspot_widget',
'实时热点追踪',
['description' => '显示最新追踪到的热点话题']
);
}
public function widget($args, $instance) {
$title = apply_filters('widget_title', $instance['title']);
$count = isset($instance['count']) ? $instance['count'] : 5;
echo $args['before_widget'];
if (!empty($title)) {
echo $args['before_title'] . $title . $args['after_title'];
}
// 获取热点数据
global $wpdb;
$table_name = $wpdb->prefix . 'hotspots';
$hotspots = $wpdb->get_results(
$wpdb->prepare(
"SELECT title, url, source, heat FROM {$table_name}
ORDER BY created_at DESC LIMIT %d",
$count
)
);
if ($hotspots) {
echo '<ul class="hotspot-list">';
foreach ($hotspots as $hotspot) {
$source_icon = $this->get_source_icon($hotspot->source);
echo '<li class="hotspot-item">';
echo '<span class="hotspot-rank">' . $source_icon . '</span>';
echo '<a href="' . esc_url($hotspot->url) . '" target="_blank" class="hotspot-link">';
echo esc_html($hotspot->title);
echo '</a>';
echo '<span class="hotspot-heat">' . esc_html($hotspot->heat) . '</span>';
echo '</li>';
}
echo '</ul>';
} else {
echo '<p>暂无热点数据</p>';
}
echo $args['after_widget'];
}
private function get_source_icon($source) {
$icons = [
'weibo' => '📱',
'zhihu' => '📚',
'baidu_trend' => '🔍',
'news_portals' => '📰'
];
return isset($icons[$source]) ? $icons[$source] : '🔥';
}
public function form($instance) {
$title = isset($instance['title']) ? $instance['title'] : '实时热点';
$count = isset($instance['count']) ? $instance['count'] : 5;
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">标题:</label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
name="<?php echo $this->get_field_name('title'); ?>" type="text"
value="<?php echo esc_attr($title); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('count'); ?>">显示数量:</label>
<input class="tiny-text" id="<?php echo $this->get_field_id('count'); ?>"
name="<?php echo $this->get_field_name('count'); ?>" type="number"
value="<?php echo esc_attr($count); ?>" min="1" max="20" />
</p>
<?php
}
public function update($new_instance, $old_instance) {
$instance = [];
$instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
$instance['count'] = (!empty($new_instance['count'])) ? intval($new_instance['count']) : 5;
return $instance;
}
}
// 注册小工具
add_action('widgets_init', function() {
register_widget('Hotspot_Widget');
});
?>
数据管理与优化策略
1. 数据库表结构设计
-- 热点数据表
CREATE TABLE IF NOT EXISTS `wp_hotspots` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(500) NOT NULL COMMENT '热点标题',
`url` varchar(1000) NOT NULL COMMENT '热点链接',
`heat` varchar(50) DEFAULT NULL COMMENT '热度值',
`source` varchar(50) NOT NULL COMMENT '来源平台',
`category` varchar(100) DEFAULT NULL COMMENT '分类标签',
`keywords` text COMMENT '关键词JSON',
`created_at` datetime NOT NULL COMMENT '创建时间',
`updated_at` datetime DEFAULT NULL COMMENT '更新时间',
`status` tinyint(1) DEFAULT '1' COMMENT '状态:1-有效,0-过期',
PRIMARY KEY (`id`),
KEY `idx_source` (`source`),
KEY `idx_created` (`created_at`),
KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='热点追踪数据表';
-- 生成内容记录表
CREATE TABLE IF NOT EXISTS `wp_ai_contents` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`hotspot_id` int(11) DEFAULT NULL COMMENT '关联热点ID',
`post_id` int(11) DEFAULT NULL COMMENT 'WordPress文章ID',
`original_title` varchar(500) NOT NULL COMMENT '原始标题',
`generated_title` varchar(500) NOT NULL COMMENT '生成标题',
`content_length` int(11) DEFAULT NULL COMMENT '内容长度',
`generation_time` float DEFAULT NULL COMMENT '生成耗时',
`ai_model` varchar(50) DEFAULT NULL COMMENT '使用的AI模型',
`quality_score` float DEFAULT NULL COMMENT '质量评分',
`created_at` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_hotspot` (`hotspot_id`),
KEY `idx_post` (`post_id`),
KEY `idx_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AI生成内容记录表';
-- 性能日志表
CREATE TABLE IF NOT EXISTS `wp_fht_logs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`log_type` varchar(50) NOT NULL COMMENT '日志类型',
`message` text NOT NULL COMMENT '日志内容',
`data` text COMMENT '附加数据JSON',
`execution_time` float DEFAULT NULL COMMENT '执行时间',
`created_at` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_type` (`log_type`),
KEY `idx_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='插件运行日志表';
2. 性能优化与缓存机制
<?php
/**
* 缓存管理类
* 优化热点数据查询性能
*/
class HotspotCache {
private $cache_group = 'fht_hotspots';
private $cache_expire = 3600; // 1小时
public function get_hotspots($source = null, $limit = 10) {
$cache_key = $this->build_cache_key($source, $limit);
// 尝试从缓存获取
$cached = wp_cache_get($cache_key, $this->cache_group);
if ($cached !== false) {
return $cached;
}
// 缓存未命中,从数据库查询
global $wpdb;
$table_name = $wpdb->prefix . 'hotspots';
$query = "SELECT * FROM {$table_name} WHERE status = 1";
if ($source) {
$query .= $wpdb->prepare(" AND source = %s", $source);
}
$query .= " ORDER BY created_at DESC LIMIT %d";
$query = $wpdb->prepare($query, $limit);
$results = $wpdb->get_results($query, ARRAY_A);
// 处理结果
$processed_results = $this->process_results($results);
// 设置缓存
wp_cache_set($cache_key, $processed_results, $this->cache_group, $this->cache_expire);
return $processed_results;
}
private function build_cache_key($source, $limit) {
$key_parts = ['hotspots'];
if ($source) {
$key_parts[] = $source;
}
$key_parts[] = 'limit_' . $limit;
$key_parts[] = date('YmdH'); // 按小时缓存
return implode('_', $key_parts);
}
private function process_results($results) {
$processed = [];
foreach ($results as $result) {
// 清理数据
$processed[] = [
'id' => intval($result['id']),
'title' => htmlspecialchars_decode($result['title']),
'url' => esc_url($result['url']),
'heat' => $result['heat'],
'source' => $result['source'],
'time_ago' => $this->time_ago($result['created_at']),
'created_at' => $result['created_at']
];
}
return $processed;
}
private function time_ago($datetime) {
$time = strtotime($datetime);
$now = time();
$diff = $now - $time;
if ($diff < 3600) {
return ceil($diff / 60) . '分钟前';
} elseif ($diff < 86400) {
return ceil($diff / 3600) . '小时前';
} else {
return ceil($diff / 86400) . '天前';
}
}
/**
* 清除缓存
*/
public function clear_cache($source = null) {
if ($source) {
// 清除特定来源的缓存
$pattern = $this->cache_group . '_hotspots_' . $source . '_*';
$this->clear_pattern_cache($pattern);
} else {
// 清除所有热点缓存
$pattern = $this->cache_group . '_hotspots_*';
$this->clear_pattern_cache($pattern);
}
}
private function clear_pattern_cache($pattern) {
// 根据缓存实现方式清理
if (function_exists('wp_cache_flush_group')) {
wp_cache_flush_group($this->cache_group);
}
}
}
?>
安全与合规性考虑
1. 数据安全处理
<?php
/**
* 安全处理类
* 确保数据安全和合规性
*/
class SecurityManager {
/**
* 验证和清理热点数据
*/
public static function sanitize_hotspot_data($data) {
$sanitized = [];
// 清理标题
if (isset($data['title'])) {
$sanitized['title'] = wp_strip_all_tags($data['title']);
$sanitized['title'] = mb_substr($sanitized['title'], 0, 495); // 限制长度
}
// 验证URL
if (isset($data['url'])) {
$sanitized['url'] = esc_url_raw($data['url']);
// 检查URL是否允许
if (!self::is_allowed_url($sanitized['url'])) {
return false;
}
}
// 清理来源
if (isset($data['source'])) {
$allowed_sources = ['weibo', 'zhihu', 'baidu_trend', 'news_portals'];
$sanitized['source'] = in_array($data['source'], $allowed_sources)
? $data['source']
: 'unknown';
}
// 清理热度值
if (isset($data['heat'])) {
$sanitized['heat'] = preg_replace('/[^0-9万亿热度]/u', '', $data['heat']);
}
// 添加时间戳
$sanitized['created_at'] = current_time('mysql');
return $sanitized;
}
/**
* 检查URL是否在允许的域名内
*/
private static function is_allowed_url($url) {
$allowed_domains = [
'weibo.com',
'zhihu.com',
'baidu.com',
'sina.com.cn',
'sohu.com',
'qq.com',
'163.com'
];
$parsed = parse_url($url);
if (!isset($parsed['host'])) {
return false;
}
$host = strtolower($parsed['host']);
foreach ($allowed_domains as $domain) {
if (strpos($host, $domain) !== false) {
return true;
}
}
return false;
}
/**
* 内容合规性检查
*/
public static function content_compliance_check($content) {
$sensitive_keywords = [
'敏感词1', '敏感词2', '敏感词3' // 实际使用时应从数据库或配置文件中读取
];
$issues = [];
// 检查敏感词
foreach ($sensitive_keywords as $keyword) {
if (stripos($content, $keyword) !== false) {
$issues[] = "包含敏感词: {$keyword}";
}
}
// 检查内容长度
$content_length = mb_strlen(strip_tags($content));
if ($content_length < 300) {
$issues[] = "内容过短: {$content_length}字";
}
// 检查链接数量
$link_count = substr_count(strtolower($content), '<a href');
if ($link_count > 10) {
$issues[] = "外链过多: {$link_count}个";
}
return [
'passed' => empty($issues),
'issues' => $issues,
'score' => empty($issues) ? 100 : max(0, 100 - count($issues) * 10)
];
}
/**
* API请求频率限制
*/
public static function rate_limit_check($action, $user_id = null) {
if ($user_id === null) {
$user_id = get_current_user_id();
}
$transient_key = 'fht_rate_limit_' . $action . '_' . $user_id;
$attempts = get_transient($transient_key);
if ($attempts === false) {
$attempts = 0;
}
$limits = [
'hotspot_tracking' => 10, // 每小时10次
'content_generation' => 50, // 每天50次
'api_request' => 100 // 每小时100次
];
$limit = isset($limits[$action]) ? $limits[$action] : 10;
if ($attempts >= $limit) {
return false;
}
$attempts++;
$expiration = 3600; // 1小时
if ($action === 'content_generation') {
$expiration = 86400; // 24小时
}
set_transient($transient_key, $attempts, $expiration);
return [
'remaining' => $limit - $attempts,
'reset_time' => time() + $expiration
];
}
}
?>
故障排除与维护
1. 常见问题解决
<?php
/**
* 诊断工具类
* 帮助排查插件问题
*/
class DiagnosticTool {
public static function run_full_diagnosis() {
$results = [
'wordpress' => self::check_wordpress_environment(),
'php' => self::check_php_environment(),
'database' => self::check_database_tables(),
'permissions' => self::check_file_permissions(),
'api' => self::check_api_connections(),
'cron' => self::check_cron_jobs()
];
return $results;
}
private static function check_wordpress_environment() {
$checks = [];
// 检查WordPress版本
global $wp_version;
$checks['wp_version'] = [
'status' => version_compare($wp_version, '5.6', '>='),
'message' => "WordPress版本: {$wp_version}",
'required' => '5.6+'
];
// 检查插件是否激活
$checks['plugin_active'] = [
'status' => is_plugin_active('flexible-hotspot-tracker/flexible-hotspot-tracker.php'),
'message' => '插件激活状态'
];
// 检查必要插件
$required_plugins = [];
$checks['required_plugins'] = [
'status' => empty($required_plugins),
'message' => '必要插件检查',
'details' => $required_plugins
];
return $checks;
}
private static function check_database_tables() {
global $wpdb;
$checks = [];
$tables = [
$wpdb->prefix . 'hotspots',
$wpdb->prefix . 'ai_contents',
$wpdb->prefix . 'fht_logs'
];
foreach ($tables as $table) {
$exists = $wpdb->get_var(
$wpdb->prepare(
"SHOW TABLES LIKE %s",
$table
)
);
$checks[$table] = [
'status' => $exists === $table,
'message' => $exists ? "表 {$table} 存在" : "表 {$table} 不存在"
];
}
// 检查表结构
if ($checks[$tables[0]]['status']) {
$structure = $wpdb->get_results("DESCRIBE {$tables[0]}", ARRAY_A);
$checks['table_structure'] = [
'status' => !empty($structure),
'message' => '表结构检查',
'details' => array_column($structure, 'Field')
];
}
return $checks;
}
private static function check_api_connections() {
$checks = [];
// 测试外部API连接
$test_urls = [
'微博API' => 'https://m.weibo.cn/api/container/getIndex',
'知乎API' => 'https://www.zhihu.com/api/v3/feed/topstory/hot-lists'
];
foreach ($test_urls as $name => $url) {
$response = wp_remote_get($url, [
'timeout' => 10,
'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
]);
$checks[$name] = [
'status' => !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200,
'message' => is_wp_error($response) ? $response->get_error_message() : '连接正常'
];
}
return $checks;
}
/**
* 生成诊断报告
*/
public static function generate_report($results) {
$total_checks = 0;
$passed_checks = 0;
$report = "## 柔性热点追踪插件诊断报告nn";
$report .= "生成时间: " . current_time('Y-m-d H:i:s') . "nn";
foreach ($results as $category => $checks) {
$report .= "### " . ucfirst($category) . "nn";
foreach ($checks as $check_name => $check) {
$total_checks++;
$status_icon = $check['status'] ? '✅' : '❌';
$report .= "{$status_icon} **{$check_name}**: {$check['message']}n";
if ($check['status']) {
$passed_checks++;
}
if (isset($check['details'])) {
if (is_array($check['details'])) {
$report .= " 详情: " . implode(', ', $check['details']) . "n";
} else {
$report .= " 详情: {$check['details']}n";
}
}
if (isset($check['required'])) {
$report .= " 要求: {$check['required']}n";
}
$report .= "n";
}
}
