文章目录
- 在当今信息爆炸的时代,网络传媒机构面临着如何高效分发内容的巨大挑战。WordPress作为全球最流行的内容管理系统,通过合理的配置可以实现柔性内容智能分发,大幅提升内容传播效率和用户体验。本教程将详细介绍如何配置WordPress智能内容分发系统。
- 智能内容分发系统的核心是根据用户特征、行为数据和内容属性,动态调整内容展示策略。以下是基础架构设计: <?php /** * WordPress智能内容分发系统架构类 * 负责管理内容分发策略和用户行为分析 */ class IntelligentContentDistribution { private $user_profile; // 用户画像数据 private $content_metadata; // 内容元数据 private $distribution_rules;// 分发规则 private $performance_data; // 性能数据 /** * 初始化分发系统 */ public function __construct() { $this->user_profile = array(); $this->content_metadata = array(); $this->distribution_rules = $this->load_distribution_rules(); $this->performance_data = array(); // 添加WordPress钩子 add_action('wp_head', array($this, 'track_user_behavior')); add_filter('the_content', array($this, 'dynamic_content_adjustment')); } /** * 加载分发规则配置 * @return array 分发规则数组 */ private function load_distribution_rules() { // 从数据库或配置文件中加载规则 $default_rules = array( 'time_based' => true, // 基于时间的分发 'location_based' => true, // 基于地理位置的分发 'behavior_based' => true, // 基于用户行为的分发 'device_based' => true, // 基于设备类型的分发 'priority_levels' => array('high', 'medium', 'low') ); // 合并数据库中的自定义规则 $saved_rules = get_option('icd_distribution_rules', array()); return wp_parse_args($saved_rules, $default_rules); } /** * 跟踪用户行为 */ public function track_user_behavior() { // 获取用户基本信息 $user_id = get_current_user_id(); $user_ip = $_SERVER['REMOTE_ADDR']; $user_agent = $_SERVER['HTTP_USER_AGENT']; // 记录访问信息 $this->user_profile = array( 'user_id' => $user_id, 'ip_address' => $user_ip, 'user_agent' => $user_agent, 'access_time' => current_time('timestamp'), 'page_views' => $this->get_user_pageviews($user_id), 'preferences' => $this->analyze_user_preferences($user_id) ); // 更新用户行为数据库 $this->update_user_behavior_data(); } } ?>
- 智能分发的基础是准确理解用户需求。以下是用户画像分析模块的实现: <?php /** * 用户画像分析类 * 收集和分析用户数据,构建用户画像 */ class UserProfileAnalyzer { /** * 分析用户内容偏好 * @param int $user_id 用户ID * @return array 用户偏好数据 */ public function analyze_user_preferences($user_id) { global $wpdb; $preferences = array( 'categories' => array(), 'tags' => array(), 'authors' => array(), 'content_types' => array(), 'reading_times' => array() ); if ($user_id > 0) { // 查询用户历史浏览记录 $history = $wpdb->get_results($wpdb->prepare( "SELECT post_id, view_count, last_viewed FROM {$wpdb->prefix}user_content_history WHERE user_id = %d ORDER BY last_viewed DESC LIMIT 50", $user_id )); foreach ($history as $record) { $post_categories = wp_get_post_categories($record->post_id); $post_tags = wp_get_post_tags($record->post_id, array('fields' => 'ids')); // 统计分类偏好 foreach ($post_categories as $cat_id) { if (!isset($preferences['categories'][$cat_id])) { $preferences['categories'][$cat_id] = 0; } $preferences['categories'][$cat_id] += $record->view_count; } // 统计标签偏好 foreach ($post_tags as $tag_id) { if (!isset($preferences['tags'][$tag_id])) { $preferences['tags'][$tag_id] = 0; } $preferences['tags'][$tag_id] += $record->view_count; } } } return $preferences; } /** * 获取用户设备信息 * @return array 设备信息 */ public function get_device_info() { $user_agent = $_SERVER['HTTP_USER_AGENT']; // 检测设备类型 $device_type = 'desktop'; if (preg_match('/(android|webos|iphone|ipad|ipod|blackberry|windows phone)/i', $user_agent)) { $device_type = 'mobile'; } // 检测浏览器 $browser = 'unknown'; if (preg_match('/chrome/i', $user_agent)) { $browser = 'chrome'; } elseif (preg_match('/firefox/i', $user_agent)) { $browser = 'firefox'; } elseif (preg_match('/safari/i', $user_agent)) { $browser = 'safari'; } return array( 'type' => $device_type, 'browser' => $browser, 'screen_size' => $this->detect_screen_size() ); } /** * 检测屏幕尺寸(通过JavaScript传递) * @return string 屏幕尺寸分类 */ private function detect_screen_size() { // 实际应用中通过JavaScript获取并存储在cookie中 if (isset($_COOKIE['screen_size'])) { return sanitize_text_field($_COOKIE['screen_size']); } return 'unknown'; } } ?>
- 内容与用户的匹配是智能分发的核心。以下是匹配算法的实现: <?php /** * 内容匹配算法类 * 根据用户画像匹配最合适的内容 */ class ContentMatchingAlgorithm { private $user_profile; private $content_pool; /** * 初始化匹配算法 * @param array $user_profile 用户画像 * @param array $content_pool 内容池 */ public function __construct($user_profile, $content_pool) { $this->user_profile = $user_profile; $this->content_pool = $content_pool; } /** * 计算内容匹配分数 * @param object $content 内容对象 * @return float 匹配分数(0-100) */ public function calculate_match_score($content) { $total_score = 0; $weights = $this->get_matching_weights(); // 1. 分类匹配 (权重: 30%) $category_score = $this->calculate_category_match($content); $total_score += $category_score * $weights['category']; // 2. 标签匹配 (权重: 25%) $tag_score = $this->calculate_tag_match($content); $total_score += $tag_score * $weights['tag']; // 3. 时效性匹配 (权重: 20%) $recency_score = $this->calculate_recency_match($content); $total_score += $recency_score * $weights['recency']; // 4. 热度匹配 (权重: 15%) $popularity_score = $this->calculate_popularity_match($content); $total_score += $popularity_score * $weights['popularity']; // 5. 个性化匹配 (权重: 10%) $personalization_score = $this->calculate_personalization_match($content); $total_score += $personalization_score * $weights['personalization']; return min(100, max(0, $total_score)); } /** * 计算分类匹配度 * @param object $content 内容对象 * @return float 分类匹配分数 */ private function calculate_category_match($content) { $user_categories = $this->user_profile['preferences']['categories']; $content_categories = wp_get_post_categories($content->ID); if (empty($user_categories) || empty($content_categories)) { return 50; // 默认分数 } $match_score = 0; $max_score = 100; foreach ($content_categories as $cat_id) { if (isset($user_categories[$cat_id])) { // 用户对该分类有浏览历史,根据浏览次数计算分数 $user_views = $user_categories[$cat_id]; $match_score += min(100, $user_views * 10); } } return min($max_score, $match_score / count($content_categories)); } /** * 计算时效性匹配度 * @param object $content 内容对象 * @return float 时效性分数 */ private function calculate_recency_match($content) { $post_date = strtotime($content->post_date); $current_time = current_time('timestamp'); $days_old = ($current_time - $post_date) / (60 * 60 * 24); // 指数衰减公式:分数 = 100 * e^(-0.1 * 天数) $score = 100 * exp(-0.1 * $days_old); return max(0, min(100, $score)); } /** * 获取匹配权重配置 * @return array 权重配置 */ private function get_matching_weights() { return array( 'category' => 0.30, 'tag' => 0.25, 'recency' => 0.20, 'popularity' => 0.15, 'personalization' => 0.10 ); } } ?>
- 为了方便管理,我们需要创建一个配置界面: <?php /** * 智能分发策略配置页面 */ class ICD_Admin_Configuration { /** * 初始化管理界面 */ public function __construct() { add_action('admin_menu', array($this, 'add_admin_menu')); add_action('admin_init', array($this, 'register_settings')); } /** * 添加管理菜单 */ public function add_admin_menu() { add_options_page( '智能内容分发设置', '内容分发策略', 'manage_options', 'icd-settings', array($this, 'render_settings_page') ); } /** * 注册设置选项 */ public function register_settings() { register_setting('icd_settings_group', 'icd_distribution_rules'); register_setting('icd_settings_group', 'icd_matching_weights'); register_setting('icd_settings_group', 'icd_performance_tracking'); // 添加设置章节 add_settings_section( 'icd_main_section', '核心分发策略', array($this, 'render_main_section'), 'icd-settings' ); // 添加设置字段 add_settings_field( 'icd_time_based', '时间敏感分发', array($this, 'render_time_based_field'), 'icd-settings', 'icd_main_section' ); add_settings_field( 'icd_location_based', '地理位置分发', array($this, 'render_location_based_field'), 'icd-settings', 'icd_main_section' ); add_settings_field( 'icd_matching_weights', '匹配算法权重', array($this, 'render_matching_weights_field'), 'icd-settings', 'icd_main_section' ); } /** * 渲染设置页面 */ public function render_settings_page() { ?> <div class="wrap"> <h1>智能内容分发策略配置</h1> <form method="post" action="options.php"> <?php settings_fields('icd_settings_group'); do_settings_sections('icd-settings'); submit_button('保存配置'); ?> </form> <div class="icd-statistics"> <h2>分发效果统计</h2> <div id="icd-performance-chart"> <!-- 这里可以添加图表显示分发效果 --> <p>用户参与度提升: <span id="engagement-rate">加载中...</span></p> <p>内容点击率: <span id="click-through-rate">加载中...</span></p> <p>平均阅读时长: <span id="avg-reading-time">加载中...</span></p> </div> </div> </div> <script> // 实时加载统计数据 jQuery(document).ready(function($) { $.ajax({ url: ajaxurl, type: 'POST', data: { action: 'get_icd_statistics' }, success: function(response) { if (response.success) { $('#engagement-rate').text(response.data.engagement + '%'); $('#click-through-rate').text(response.data.ctr + '%'); $('#avg-reading-time').text(response.data.reading_time + '分钟'); } } }); }); </script> <?php } /** * 渲染时间敏感分发字段 */ public function render_time_based_field() { $options = get_option('icd_distribution_rules'); $checked = isset($options['time_based']) ? $options['time_based'] : true; ?> <input type="checkbox" name="icd_distribution_rules[time_based]" value="1" <?php checked(1, $checked); ?>> <label>启用基于时间的智能分发</label> <p class="description">根据用户活跃时间和内容发布时间优化分发时机</p> <div style="margin-top: 10px;"> <label>高峰时段权重:</label> <input type="number" name="icd_distribution_rules[peak_weight]" value="<?php echo isset($options['peak_weight']) ? $options['peak_weight'] : 1.5; ?>" step="0.1" min="0.5" max="3" style="width: 80px;"> <p class="description">高峰时段内容曝光权重倍数 (0.5-3)</p> </div> <?php } } ?>
- 智能分发系统需要高效的性能支持: <?php /** * 智能分发缓存系统 * 优化分发性能,减少数据库查询 */ class ICD_Cache_System { private $cache_group = 'icd_distribution'; private $cache_expiration = 3600; // 1小时 /** * 获取缓存内容 * @param string $key 缓存键 * @param string $user_context 用户上下文 * @return mixed 缓存数据 */ public function get_cached_content($key, $user_context = '') { $cache_key = $this->generate_cache_key($key, $user_context); // 尝试从缓存获取 $cached = wp_cache_get($cache_key, $this->cache_group); if ($cached !== false) { return $cached; } return false; } /** * 设置缓存 * @param string $key 缓存键 * @param mixed $data 缓存数据 * @param string $user_context 用户上下文 * @param int $expiration 过期时间 */ public function set_cached_content($key, $data, $user_context = '', $expiration = null) { $cache_key = $this->generate_cache_key($key, $user_context); $expire = $expiration ?: $this->cache_expiration; wp_cache_set($cache_key, $data, $this->cache_group, $expire); } /** * 生成缓存键 * @param string $key 基础键 * @param string $user_context 用户上下文 * @return string 完整缓存键 */ private function generate_cache_key($key, $user_context) { if ($user_context) { return $key . '_' . md5($user_context); } return $key; } /** * 清除用户相关缓存 * @param int $user_id 用户ID */ public function clear_user_cache($user_id) { global $wpdb; // 获取所有用户相关的缓存键 $pattern = $this->cache_group . '_user_' . $user_id . '_%'; // 这里需要根据实际缓存实现进行调整 // 如果是使用Redis或Memcached,可以使用相应的清除模式 } /** * 预加载热门内容 */ public function preload_popular_content() { // 获取热门内容ID $popular_posts = $this->get_popular_posts(20); foreach ($popular_posts as $post) { // 为不同用户群体预生成内容 $user_segments = array('new_user', 'returning_user', 'power_user'); foreach ($user_segments as $segment) { $content = $this->prepare_personalized_content($post, $segment); $cache_key = 'post_' . $post->ID . '_segment_' . $segment; $this->set_cached_content($cache_key, $content, '', 1800); // 缓存30分钟 } } } /** * 获取热门文章 * @param int $limit 数量限制 * @return array 热门文章数组 */ private function get_popular_posts($limit = 10) { global $wpdb; $cache_key = 'popular_posts_' . $limit; $cached = $this->get_cached_content($cache_key); if ($cached !== false) { return $cached; } $query = $wpdb->prepare( "SELECT p.ID, p.post_title, COUNT(v.id) as view_count, AVG(r.meta_value) as avg_rating FROM {$wpdb->posts} p LEFT JOIN {$wpdb->prefix}post_views v ON p.ID = v.post_id LEFT JOIN {$wpdb->postmeta} r ON p.ID = r.post_id AND r.meta_key = 'user_rating' WHERE p.post_type = 'post' AND p.post_status = 'publish' AND p.post_date > DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY p.ID ORDER BY view_count DESC, avg_rating DESC LIMIT %d", $limit ); $results = $wpdb->get_results($query); $this->set_cached_content($cache_key, $results, '', 900); // 缓存15分钟 return $results; } } ?>
- 为了持续优化分发效果,需要建立A/B测试系统: <?php /** * A/B测试管理系统 * 用于测试不同分发策略的效果 */ class AB_Testing_Manager { private $active_tests; private $test_results; /** * 初始化A/B测试系统 */ public function __construct() { $this->active_tests = get_option('icd_ab_tests', array()); $this->test_results = array(); add_action('wp_footer', array($this, 'track_test_interactions')); } /** * 创建新的A/B测试 * @param string $test_name 测试名称 * @param array $variants 测试变体 * @param string $metric 评估指标 * @param int $duration 测试时长(天) */ public function create_test($test_name, $variants, $metric, $duration = 14) { $test_id = sanitize_title($test_name) . '_' . time(); $test_config = array( 'id' => $test_id, 'name' => $test_name, 'variants' => $variants, 'metric' => $metric, 'start_date' => current_time('mysql'), 'end_date' => date('Y-m-d H:i:s', strtotime("+{$duration} days")), 'status' => 'active', 'participants' => array(), 'results' => array() ); $this->active_tests[$test_id] = $test_config; update_option('icd_ab_tests', $this->active_tests); return $test_id; } /** * 为用户分配测试变体 * @param string $test_id 测试ID * @param int $user_id 用户ID * @return string 分配的变体 */ public function assign_variant($test_id, $user_id) { if (!isset($this->active_tests[$test_id])) { return 'control'; } $test = $this->active_tests[$test_id]; // 检查用户是否已参与测试 if (isset($test['participants'][$user_id])) { return $test['participants'][$user_id]; } // 随机分配变体(可改为更智能的分配算法) $variant_keys = array_keys($test['variants']); $assigned_variant = $variant_keys[array_rand($variant_keys)]; // 记录分配 $this->active_tests[$test_id]['participants'][$user_id] = $assigned_variant; update_option('icd_ab_tests', $this->active_tests); return $assigned_variant; } /** * 记录测试结果 * @param string $test_id 测试ID * @param string $variant 变体名称 * @param string $metric 指标名称 * @param float $value 指标值 */ public function record_result($test_id, $variant, $metric, $value) { if (!isset($this->test_results[$test_id])) { $this->test_results[$test_id] = array(); } if (!isset($this->test_results[$test_id][$variant])) { $this->test_results[$test_id][$variant] = array(); } if (!isset($this->test_results[$test_id][$variant][$metric])) { $this->test_results[$test_id][$variant][$metric] = array(); } $this->test_results[$test_id][$variant][$metric][] = $value; // 定期保存到数据库 if (count($this->test_results[$test_id][$variant][$metric]) % 100 === 0) { $this->save_test_results($test_id); } } /** * 分析测试结果 * @param string $test_id 测试ID * @return array 分析结果 */ public function analyze_results($test_id) { if (!isset($this->active_tests[$test_id]) || !isset($this->test_results[$test_id])) { return array('error' => '测试不存在或没有数据'); } $test = $this->active_tests[$test_id]; $analysis = array( 'test_id' => $test_id, 'test_name' => $test['name'], 'total_participants' => count($test['participants']), 'variants' => array() ); foreach ($test['variants'] as $variant_name => $variant_config) { if (!isset($this->test_results[$test_id][$variant_name])) { continue; } $variant_data = $this->test_results[$test_id][$variant_name]; $metric_values = isset($variant_data[$test['metric']]) ? $variant_data[$test['metric']] : array(); $analysis['variants'][$variant_name] = array( 'participants' => count(array_keys($test['participants'], $variant_name)), 'metric' => $test['metric'], 'mean' => $this->calculate_mean($metric_values), 'std_dev' => $this->calculate_std_dev($metric_values), 'confidence_interval' => $this->calculate_confidence_interval($metric_values), 'improvement' => $this->calculate_improvement($test_id, 'control', $variant_name) ); } // 确定优胜变体 $analysis['winner'] = $this->determine_winner($analysis['variants']); return $analysis; } /** * 计算平均值 */ private function calculate_mean($values) { if (empty($values)) return 0; return array_sum($values) / count($values); } /** * 计算标准差 */ private function calculate_std_dev($values) { if (count($values) < 2) return 0; $mean = $this->calculate_mean($values); $sum = 0; foreach ($values as $value) { $sum += pow($value - $mean, 2); } return sqrt($sum / (count($values) - 1)); } } ?>
- 确保系统稳定运行需要监控机制: <?php /** * 系统监控与报警类 * 监控分发系统性能,及时发现问题 */ class ICD_Monitoring_System { private $performance_metrics; private $alert_thresholds; private $notification_emails; /** * 初始化监控系统 */ public function __construct() { $this->performance_metrics = array(); $this->alert_thresholds = $this->load_alert_thresholds(); $this->notification_emails = get_option('icd_alert_emails', get_option('admin_email')); // 定期检查性能 add_action('icd_hourly_monitoring', array($this, 'perform_health_check')); if (!wp_next_scheduled('icd_hourly_monitoring')) { wp_schedule_event(time(), 'hourly', 'icd_hourly_monitoring'); } } /** * 记录性能指标 * @param string $metric_name 指标名称 * @param float $value 指标值 * @param array $tags 标签信息 */ public function record_metric($metric_name, $value, $tags = array()) { $timestamp = microtime(true); $metric_key = $metric_name . '_' . date('Y-m-d_H'); if (!isset($this->performance_metrics[$metric_key])) { $this->performance_metrics[$metric_key] = array(); } $this->performance_metrics[$metric_key][] = array( 'timestamp' => $timestamp, 'value' => $value, 'tags' => $tags ); // 检查是否触发警报 $this->check_alert_thresholds($metric_name, $value, $tags); // 定期保存到数据库 if (count($this->performance_metrics[$metric_key]) % 100 === 0) { $this->save_metrics_to_db(); } } /** * 执行健康检查 */ public function perform_health_check() { $health_status = array( 'database' => $this->check_database_health(), 'cache' => $this->check_cache_health(), 'api' => $this->check_api_health(), 'performance' => $this->check_performance_health() ); // 记录健康状态 $this->record_metric('health_check', $health_status['database']['score'] * 0.3 + $health_status['cache']['score'] * 0.3 + $health_status['api']['score'] * 0.2 + $health_status['performance']['score'] * 0.2 ); // 发送报告 if ($this->should_send_report()) { $this->send_health_report($health_status); } // 清理旧数据 $this->cleanup_old_metrics(); } /** * 检查数据库健康状态 */ private function check_database_health() { global $wpdb; $results = array( 'score' => 100, 'issues' => array() ); // 检查数据库连接 $start_time = microtime(true); $wpdb->get_results("SELECT 1"); $query_time = microtime(true) - $start_time; if ($query_time > 0.5) { // 超过0.5秒 $results['score'] -= 20; $results['issues'][] = "数据库查询缓慢: {$query_time}秒"; } // 检查表状态 $tables = $wpdb->get_results("SHOW TABLE STATUS"); foreach ($tables as $table) { if ($table->Data_length > 100 * 1024 * 1024) { // 超过100MB $results['score'] -= 5; $results['issues'][] = "表 {$table->Name} 过大: " . round($table->Data_length / (1024 * 1024), 2) . "MB"; } } return $results; } /** * 发送警报邮件 */ private function send_alert($subject, $message, $level = 'warning') { $to = $this->notification_emails; $headers = array('Content-Type: text/html; charset=UTF-8'); $email_content = " <html> <head> <style> .alert { padding: 20px; border-left: 5px solid; } .warning { background: #fff3cd; border-color: #ffc107; } .critical { background: #f8d7da; border-color: #dc3545; } .info { background: #d1ecf1; border-color: #17a2b8; } </style> </head> <body> <div class='alert {$level}'> <h2>{$subject}</h2> <p>时间: " . date('Y-m-d H:i:s') . "</p> <div>{$message}</div> <hr> <p>此邮件来自 WordPress 智能内容分发系统监控</p> </div> </body> </html> "; wp_mail($to, "[ICD Alert] {$subject}", $email_content, $headers); } } ?>
在当今信息爆炸的时代,网络传媒机构面临着如何高效分发内容的巨大挑战。WordPress作为全球最流行的内容管理系统,通过合理的配置可以实现柔性内容智能分发,大幅提升内容传播效率和用户体验。本教程将详细介绍如何配置WordPress智能内容分发系统。
智能内容分发系统的核心是根据用户特征、行为数据和内容属性,动态调整内容展示策略。以下是基础架构设计:
<?php
/**
* WordPress智能内容分发系统架构类
* 负责管理内容分发策略和用户行为分析
*/
class IntelligentContentDistribution {
private $user_profile; // 用户画像数据
private $content_metadata; // 内容元数据
private $distribution_rules;// 分发规则
private $performance_data; // 性能数据
/**
* 初始化分发系统
*/
public function __construct() {
$this->user_profile = array();
$this->content_metadata = array();
$this->distribution_rules = $this->load_distribution_rules();
$this->performance_data = array();
// 添加WordPress钩子
add_action('wp_head', array($this, 'track_user_behavior'));
add_filter('the_content', array($this, 'dynamic_content_adjustment'));
}
/**
* 加载分发规则配置
* @return array 分发规则数组
*/
private function load_distribution_rules() {
// 从数据库或配置文件中加载规则
$default_rules = array(
'time_based' => true, // 基于时间的分发
'location_based' => true, // 基于地理位置的分发
'behavior_based' => true, // 基于用户行为的分发
'device_based' => true, // 基于设备类型的分发
'priority_levels' => array('high', 'medium', 'low')
);
// 合并数据库中的自定义规则
$saved_rules = get_option('icd_distribution_rules', array());
return wp_parse_args($saved_rules, $default_rules);
}
/**
* 跟踪用户行为
*/
public function track_user_behavior() {
// 获取用户基本信息
$user_id = get_current_user_id();
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// 记录访问信息
$this->user_profile = array(
'user_id' => $user_id,
'ip_address' => $user_ip,
'user_agent' => $user_agent,
'access_time' => current_time('timestamp'),
'page_views' => $this->get_user_pageviews($user_id),
'preferences' => $this->analyze_user_preferences($user_id)
);
// 更新用户行为数据库
$this->update_user_behavior_data();
}
}
?>
智能分发的基础是准确理解用户需求。以下是用户画像分析模块的实现:
<?php
/**
* 用户画像分析类
* 收集和分析用户数据,构建用户画像
*/
class UserProfileAnalyzer {
/**
* 分析用户内容偏好
* @param int $user_id 用户ID
* @return array 用户偏好数据
*/
public function analyze_user_preferences($user_id) {
global $wpdb;
$preferences = array(
'categories' => array(),
'tags' => array(),
'authors' => array(),
'content_types' => array(),
'reading_times' => array()
);
if ($user_id > 0) {
// 查询用户历史浏览记录
$history = $wpdb->get_results($wpdb->prepare(
"SELECT post_id, view_count, last_viewed
FROM {$wpdb->prefix}user_content_history
WHERE user_id = %d
ORDER BY last_viewed DESC
LIMIT 50",
$user_id
));
foreach ($history as $record) {
$post_categories = wp_get_post_categories($record->post_id);
$post_tags = wp_get_post_tags($record->post_id, array('fields' => 'ids'));
// 统计分类偏好
foreach ($post_categories as $cat_id) {
if (!isset($preferences['categories'][$cat_id])) {
$preferences['categories'][$cat_id] = 0;
}
$preferences['categories'][$cat_id] += $record->view_count;
}
// 统计标签偏好
foreach ($post_tags as $tag_id) {
if (!isset($preferences['tags'][$tag_id])) {
$preferences['tags'][$tag_id] = 0;
}
$preferences['tags'][$tag_id] += $record->view_count;
}
}
}
return $preferences;
}
/**
* 获取用户设备信息
* @return array 设备信息
*/
public function get_device_info() {
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// 检测设备类型
$device_type = 'desktop';
if (preg_match('/(android|webos|iphone|ipad|ipod|blackberry|windows phone)/i', $user_agent)) {
$device_type = 'mobile';
}
// 检测浏览器
$browser = 'unknown';
if (preg_match('/chrome/i', $user_agent)) {
$browser = 'chrome';
} elseif (preg_match('/firefox/i', $user_agent)) {
$browser = 'firefox';
} elseif (preg_match('/safari/i', $user_agent)) {
$browser = 'safari';
}
return array(
'type' => $device_type,
'browser' => $browser,
'screen_size' => $this->detect_screen_size()
);
}
/**
* 检测屏幕尺寸(通过JavaScript传递)
* @return string 屏幕尺寸分类
*/
private function detect_screen_size() {
// 实际应用中通过JavaScript获取并存储在cookie中
if (isset($_COOKIE['screen_size'])) {
return sanitize_text_field($_COOKIE['screen_size']);
}
return 'unknown';
}
}
?>
内容与用户的匹配是智能分发的核心。以下是匹配算法的实现:
<?php
/**
* 内容匹配算法类
* 根据用户画像匹配最合适的内容
*/
class ContentMatchingAlgorithm {
private $user_profile;
private $content_pool;
/**
* 初始化匹配算法
* @param array $user_profile 用户画像
* @param array $content_pool 内容池
*/
public function __construct($user_profile, $content_pool) {
$this->user_profile = $user_profile;
$this->content_pool = $content_pool;
}
/**
* 计算内容匹配分数
* @param object $content 内容对象
* @return float 匹配分数(0-100)
*/
public function calculate_match_score($content) {
$total_score = 0;
$weights = $this->get_matching_weights();
// 1. 分类匹配 (权重: 30%)
$category_score = $this->calculate_category_match($content);
$total_score += $category_score * $weights['category'];
// 2. 标签匹配 (权重: 25%)
$tag_score = $this->calculate_tag_match($content);
$total_score += $tag_score * $weights['tag'];
// 3. 时效性匹配 (权重: 20%)
$recency_score = $this->calculate_recency_match($content);
$total_score += $recency_score * $weights['recency'];
// 4. 热度匹配 (权重: 15%)
$popularity_score = $this->calculate_popularity_match($content);
$total_score += $popularity_score * $weights['popularity'];
// 5. 个性化匹配 (权重: 10%)
$personalization_score = $this->calculate_personalization_match($content);
$total_score += $personalization_score * $weights['personalization'];
return min(100, max(0, $total_score));
}
/**
* 计算分类匹配度
* @param object $content 内容对象
* @return float 分类匹配分数
*/
private function calculate_category_match($content) {
$user_categories = $this->user_profile['preferences']['categories'];
$content_categories = wp_get_post_categories($content->ID);
if (empty($user_categories) || empty($content_categories)) {
return 50; // 默认分数
}
$match_score = 0;
$max_score = 100;
foreach ($content_categories as $cat_id) {
if (isset($user_categories[$cat_id])) {
// 用户对该分类有浏览历史,根据浏览次数计算分数
$user_views = $user_categories[$cat_id];
$match_score += min(100, $user_views * 10);
}
}
return min($max_score, $match_score / count($content_categories));
}
/**
* 计算时效性匹配度
* @param object $content 内容对象
* @return float 时效性分数
*/
private function calculate_recency_match($content) {
$post_date = strtotime($content->post_date);
$current_time = current_time('timestamp');
$days_old = ($current_time - $post_date) / (60 * 60 * 24);
// 指数衰减公式:分数 = 100 * e^(-0.1 * 天数)
$score = 100 * exp(-0.1 * $days_old);
return max(0, min(100, $score));
}
/**
* 获取匹配权重配置
* @return array 权重配置
*/
private function get_matching_weights() {
return array(
'category' => 0.30,
'tag' => 0.25,
'recency' => 0.20,
'popularity' => 0.15,
'personalization' => 0.10
);
}
}
?>
为了方便管理,我们需要创建一个配置界面:
<?php
/**
* 智能分发策略配置页面
*/
class ICD_Admin_Configuration {
/**
* 初始化管理界面
*/
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_options_page(
'智能内容分发设置',
'内容分发策略',
'manage_options',
'icd-settings',
array($this, 'render_settings_page')
);
}
/**
* 注册设置选项
*/
public function register_settings() {
register_setting('icd_settings_group', 'icd_distribution_rules');
register_setting('icd_settings_group', 'icd_matching_weights');
register_setting('icd_settings_group', 'icd_performance_tracking');
// 添加设置章节
add_settings_section(
'icd_main_section',
'核心分发策略',
array($this, 'render_main_section'),
'icd-settings'
);
// 添加设置字段
add_settings_field(
'icd_time_based',
'时间敏感分发',
array($this, 'render_time_based_field'),
'icd-settings',
'icd_main_section'
);
add_settings_field(
'icd_location_based',
'地理位置分发',
array($this, 'render_location_based_field'),
'icd-settings',
'icd_main_section'
);
add_settings_field(
'icd_matching_weights',
'匹配算法权重',
array($this, 'render_matching_weights_field'),
'icd-settings',
'icd_main_section'
);
}
/**
* 渲染设置页面
*/
public function render_settings_page() {
?>
<div class="wrap">
<h1>智能内容分发策略配置</h1>
<form method="post" action="options.php">
<?php
settings_fields('icd_settings_group');
do_settings_sections('icd-settings');
submit_button('保存配置');
?>
</form>
<div class="icd-statistics">
<h2>分发效果统计</h2>
<div id="icd-performance-chart">
<!-- 这里可以添加图表显示分发效果 -->
<p>用户参与度提升: <span id="engagement-rate">加载中...</span></p>
<p>内容点击率: <span id="click-through-rate">加载中...</span></p>
<p>平均阅读时长: <span id="avg-reading-time">加载中...</span></p>
</div>
</div>
</div>
<script>
// 实时加载统计数据
jQuery(document).ready(function($) {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'get_icd_statistics'
},
success: function(response) {
if (response.success) {
$('#engagement-rate').text(response.data.engagement + '%');
$('#click-through-rate').text(response.data.ctr + '%');
$('#avg-reading-time').text(response.data.reading_time + '分钟');
}
}
});
});
</script>
<?php
}
/**
* 渲染时间敏感分发字段
*/
public function render_time_based_field() {
$options = get_option('icd_distribution_rules');
$checked = isset($options['time_based']) ? $options['time_based'] : true;
?>
<input type="checkbox" name="icd_distribution_rules[time_based]" value="1" <?php checked(1, $checked); ?>>
<label>启用基于时间的智能分发</label>
<p class="description">根据用户活跃时间和内容发布时间优化分发时机</p>
<div style="margin-top: 10px;">
<label>高峰时段权重:</label>
<input type="number" name="icd_distribution_rules[peak_weight]"
value="<?php echo isset($options['peak_weight']) ? $options['peak_weight'] : 1.5; ?>"
step="0.1" min="0.5" max="3" style="width: 80px;">
<p class="description">高峰时段内容曝光权重倍数 (0.5-3)</p>
</div>
<?php
}
}
?>
智能分发系统需要高效的性能支持:
<?php
/**
* 智能分发缓存系统
* 优化分发性能,减少数据库查询
*/
class ICD_Cache_System {
private $cache_group = 'icd_distribution';
private $cache_expiration = 3600; // 1小时
/**
* 获取缓存内容
* @param string $key 缓存键
* @param string $user_context 用户上下文
* @return mixed 缓存数据
*/
public function get_cached_content($key, $user_context = '') {
$cache_key = $this->generate_cache_key($key, $user_context);
// 尝试从缓存获取
$cached = wp_cache_get($cache_key, $this->cache_group);
if ($cached !== false) {
return $cached;
}
return false;
}
/**
* 设置缓存
* @param string $key 缓存键
* @param mixed $data 缓存数据
* @param string $user_context 用户上下文
* @param int $expiration 过期时间
*/
public function set_cached_content($key, $data, $user_context = '', $expiration = null) {
$cache_key = $this->generate_cache_key($key, $user_context);
$expire = $expiration ?: $this->cache_expiration;
wp_cache_set($cache_key, $data, $this->cache_group, $expire);
}
/**
* 生成缓存键
* @param string $key 基础键
* @param string $user_context 用户上下文
* @return string 完整缓存键
*/
private function generate_cache_key($key, $user_context) {
if ($user_context) {
return $key . '_' . md5($user_context);
}
return $key;
}
/**
* 清除用户相关缓存
* @param int $user_id 用户ID
*/
public function clear_user_cache($user_id) {
global $wpdb;
// 获取所有用户相关的缓存键
$pattern = $this->cache_group . '_user_' . $user_id . '_%';
// 这里需要根据实际缓存实现进行调整
// 如果是使用Redis或Memcached,可以使用相应的清除模式
}
/**
* 预加载热门内容
*/
public function preload_popular_content() {
// 获取热门内容ID
$popular_posts = $this->get_popular_posts(20);
foreach ($popular_posts as $post) {
// 为不同用户群体预生成内容
$user_segments = array('new_user', 'returning_user', 'power_user');
foreach ($user_segments as $segment) {
$content = $this->prepare_personalized_content($post, $segment);
$cache_key = 'post_' . $post->ID . '_segment_' . $segment;
$this->set_cached_content($cache_key, $content, '', 1800); // 缓存30分钟
}
}
}
/**
* 获取热门文章
* @param int $limit 数量限制
* @return array 热门文章数组
*/
private function get_popular_posts($limit = 10) {
global $wpdb;
$cache_key = 'popular_posts_' . $limit;
$cached = $this->get_cached_content($cache_key);
if ($cached !== false) {
return $cached;
}
$query = $wpdb->prepare(
"SELECT p.ID, p.post_title,
COUNT(v.id) as view_count,
AVG(r.meta_value) as avg_rating
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->prefix}post_views v ON p.ID = v.post_id
LEFT JOIN {$wpdb->postmeta} r ON p.ID = r.post_id AND r.meta_key = 'user_rating'
WHERE p.post_type = 'post'
AND p.post_status = 'publish'
AND p.post_date > DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY p.ID
ORDER BY view_count DESC, avg_rating DESC
LIMIT %d",
$limit
);
$results = $wpdb->get_results($query);
$this->set_cached_content($cache_key, $results, '', 900); // 缓存15分钟
return $results;
}
}
?>
为了持续优化分发效果,需要建立A/B测试系统:
<?php
/**
* A/B测试管理系统
* 用于测试不同分发策略的效果
*/
class AB_Testing_Manager {
private $active_tests;
private $test_results;
/**
* 初始化A/B测试系统
*/
public function __construct() {
$this->active_tests = get_option('icd_ab_tests', array());
$this->test_results = array();
add_action('wp_footer', array($this, 'track_test_interactions'));
}
/**
* 创建新的A/B测试
* @param string $test_name 测试名称
* @param array $variants 测试变体
* @param string $metric 评估指标
* @param int $duration 测试时长(天)
*/
public function create_test($test_name, $variants, $metric, $duration = 14) {
$test_id = sanitize_title($test_name) . '_' . time();
$test_config = array(
'id' => $test_id,
'name' => $test_name,
'variants' => $variants,
'metric' => $metric,
'start_date' => current_time('mysql'),
'end_date' => date('Y-m-d H:i:s', strtotime("+{$duration} days")),
'status' => 'active',
'participants' => array(),
'results' => array()
);
$this->active_tests[$test_id] = $test_config;
update_option('icd_ab_tests', $this->active_tests);
return $test_id;
}
/**
* 为用户分配测试变体
* @param string $test_id 测试ID
* @param int $user_id 用户ID
* @return string 分配的变体
*/
public function assign_variant($test_id, $user_id) {
if (!isset($this->active_tests[$test_id])) {
return 'control';
}
$test = $this->active_tests[$test_id];
// 检查用户是否已参与测试
if (isset($test['participants'][$user_id])) {
return $test['participants'][$user_id];
}
// 随机分配变体(可改为更智能的分配算法)
$variant_keys = array_keys($test['variants']);
$assigned_variant = $variant_keys[array_rand($variant_keys)];
// 记录分配
$this->active_tests[$test_id]['participants'][$user_id] = $assigned_variant;
update_option('icd_ab_tests', $this->active_tests);
return $assigned_variant;
}
/**
* 记录测试结果
* @param string $test_id 测试ID
* @param string $variant 变体名称
* @param string $metric 指标名称
* @param float $value 指标值
*/
public function record_result($test_id, $variant, $metric, $value) {
if (!isset($this->test_results[$test_id])) {
$this->test_results[$test_id] = array();
}
if (!isset($this->test_results[$test_id][$variant])) {
$this->test_results[$test_id][$variant] = array();
}
if (!isset($this->test_results[$test_id][$variant][$metric])) {
$this->test_results[$test_id][$variant][$metric] = array();
}
$this->test_results[$test_id][$variant][$metric][] = $value;
// 定期保存到数据库
if (count($this->test_results[$test_id][$variant][$metric]) % 100 === 0) {
$this->save_test_results($test_id);
}
}
/**
* 分析测试结果
* @param string $test_id 测试ID
* @return array 分析结果
*/
public function analyze_results($test_id) {
if (!isset($this->active_tests[$test_id]) || !isset($this->test_results[$test_id])) {
return array('error' => '测试不存在或没有数据');
}
$test = $this->active_tests[$test_id];
$analysis = array(
'test_id' => $test_id,
'test_name' => $test['name'],
'total_participants' => count($test['participants']),
'variants' => array()
);
foreach ($test['variants'] as $variant_name => $variant_config) {
if (!isset($this->test_results[$test_id][$variant_name])) {
continue;
}
$variant_data = $this->test_results[$test_id][$variant_name];
$metric_values = isset($variant_data[$test['metric']]) ? $variant_data[$test['metric']] : array();
$analysis['variants'][$variant_name] = array(
'participants' => count(array_keys($test['participants'], $variant_name)),
'metric' => $test['metric'],
'mean' => $this->calculate_mean($metric_values),
'std_dev' => $this->calculate_std_dev($metric_values),
'confidence_interval' => $this->calculate_confidence_interval($metric_values),
'improvement' => $this->calculate_improvement($test_id, 'control', $variant_name)
);
}
// 确定优胜变体
$analysis['winner'] = $this->determine_winner($analysis['variants']);
return $analysis;
}
/**
* 计算平均值
*/
private function calculate_mean($values) {
if (empty($values)) return 0;
return array_sum($values) / count($values);
}
/**
* 计算标准差
*/
private function calculate_std_dev($values) {
if (count($values) < 2) return 0;
$mean = $this->calculate_mean($values);
$sum = 0;
foreach ($values as $value) {
$sum += pow($value - $mean, 2);
}
return sqrt($sum / (count($values) - 1));
}
}
?>
确保系统稳定运行需要监控机制:
<?php
/**
* 系统监控与报警类
* 监控分发系统性能,及时发现问题
*/
class ICD_Monitoring_System {
private $performance_metrics;
private $alert_thresholds;
private $notification_emails;
/**
* 初始化监控系统
*/
public function __construct() {
$this->performance_metrics = array();
$this->alert_thresholds = $this->load_alert_thresholds();
$this->notification_emails = get_option('icd_alert_emails', get_option('admin_email'));
// 定期检查性能
add_action('icd_hourly_monitoring', array($this, 'perform_health_check'));
if (!wp_next_scheduled('icd_hourly_monitoring')) {
wp_schedule_event(time(), 'hourly', 'icd_hourly_monitoring');
}
}
/**
* 记录性能指标
* @param string $metric_name 指标名称
* @param float $value 指标值
* @param array $tags 标签信息
*/
public function record_metric($metric_name, $value, $tags = array()) {
$timestamp = microtime(true);
$metric_key = $metric_name . '_' . date('Y-m-d_H');
if (!isset($this->performance_metrics[$metric_key])) {
$this->performance_metrics[$metric_key] = array();
}
$this->performance_metrics[$metric_key][] = array(
'timestamp' => $timestamp,
'value' => $value,
'tags' => $tags
);
// 检查是否触发警报
$this->check_alert_thresholds($metric_name, $value, $tags);
// 定期保存到数据库
if (count($this->performance_metrics[$metric_key]) % 100 === 0) {
$this->save_metrics_to_db();
}
}
/**
* 执行健康检查
*/
public function perform_health_check() {
$health_status = array(
'database' => $this->check_database_health(),
'cache' => $this->check_cache_health(),
'api' => $this->check_api_health(),
'performance' => $this->check_performance_health()
);
// 记录健康状态
$this->record_metric('health_check',
$health_status['database']['score'] * 0.3 +
$health_status['cache']['score'] * 0.3 +
$health_status['api']['score'] * 0.2 +
$health_status['performance']['score'] * 0.2
);
// 发送报告
if ($this->should_send_report()) {
$this->send_health_report($health_status);
}
// 清理旧数据
$this->cleanup_old_metrics();
}
/**
* 检查数据库健康状态
*/
private function check_database_health() {
global $wpdb;
$results = array(
'score' => 100,
'issues' => array()
);
// 检查数据库连接
$start_time = microtime(true);
$wpdb->get_results("SELECT 1");
$query_time = microtime(true) - $start_time;
if ($query_time > 0.5) { // 超过0.5秒
$results['score'] -= 20;
$results['issues'][] = "数据库查询缓慢: {$query_time}秒";
}
// 检查表状态
$tables = $wpdb->get_results("SHOW TABLE STATUS");
foreach ($tables as $table) {
if ($table->Data_length > 100 * 1024 * 1024) { // 超过100MB
$results['score'] -= 5;
$results['issues'][] = "表 {$table->Name} 过大: " .
round($table->Data_length / (1024 * 1024), 2) . "MB";
}
}
return $results;
}
/**
* 发送警报邮件
*/
private function send_alert($subject, $message, $level = 'warning') {
$to = $this->notification_emails;
$headers = array('Content-Type: text/html; charset=UTF-8');
$email_content = "
<html>
<head>
<style>
.alert { padding: 20px; border-left: 5px solid; }
.warning { background: #fff3cd; border-color: #ffc107; }
.critical { background: #f8d7da; border-color: #dc3545; }
.info { background: #d1ecf1; border-color: #17a2b8; }
</style>
</head>
<body>
<div class='alert {$level}'>
<h2>{$subject}</h2>
<p>时间: " . date('Y-m-d H:i:s') . "</p>
<div>{$message}</div>
<hr>
<p>此邮件来自 WordPress 智能内容分发系统监控</p>
</div>
</body>
</html>
";
wp_mail($to, "[ICD Alert] {$subject}", $email_content, $headers);
}
}
?>
-
环境要求检查
- PHP 7.4+ 版本
- MySQL 5.7+ 或 MariaDB 10.3+
- WordPress 5.8+
- 至少 256MB PHP 内存限制
- 安装配置流程
# 1. 创建插件目录
cd wp-content/plugins
mkdir intelligent-content-distribution
# 2. 复制所有类文件
cp *.php intelligent-content-distribution/
# 3. 创建主插件文件
cat > intelligent-content-distribution.php << 'EOF'
<?php
/**
* Plugin Name: 智能内容分发系统
* Description: WordPress柔性内容智能分发策略配置
* Version: 1.0.0
* Author: 网络传媒技术团队
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('ICD_VERSION', '1.0.0');
define('ICD_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ICD_PLUGIN_URL', plugin_dir_url(__FILE__));
// 自动加载类文件
spl_autoload_register(function ($class_name) {
$class_map = array(
'IntelligentContentDistribution' => 'class-intelligent-distribution.php',
'UserProfileAnalyzer' => 'class-user-analyzer.php',
'ContentMatchingAlgorithm' => 'class-matching-algorithm.php',
'ICD_Admin_Configuration' => 'class-admin-config.php',
'ICD_Cache_System' => 'class-cache-system.php',
'AB_Testing_Manager' => 'class-ab-testing.php',
'ICD_Monitoring_System' => 'class-monitoring.php'
);
if (isset($class_map[$class_name])) {
require_once ICD_PLUGIN_DIR . 'includes/' . $class_map[$class_name];
}
});
// 初始化插件
add_action('plugins_loaded', 'icd_initialize_plugin');
function icd_initialize_plugin() {
// 检查依赖
if (!class_exists('WP_Http')) {
require_once ABSPATH . WPINC . '/class-http.php';
}
// 初始化核心组件
$distribution_system = new IntelligentContentDistribution();
$admin_config = new ICD_Admin_Configuration();
$monitoring = new ICD_Monitoring_System();
// 注册激活/停用钩子
register_activation_hook(__FILE__, 'icd_activate_plugin');
register_deactivation_hook(__FILE__, 'icd_deactivate_plugin');
}
function icd_activate_plugin() {
// 创建数据库表
icd_create_database_tables();
// 设置默认选项
icd_set_default_options();
// 添加管理员通知
set_transient('icd_activation_notice', true, 60);
}
function icd_create_database_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$tables = array(
"{$wpdb->prefix}icd_user_behavior" => "
CREATE TABLE {$wpdb->prefix}icd_user_behavior (
id bigint(20) NOT NULL AUTO_INCREMENT,
user_id bigint(20) NOT NULL,
post_id bigint(20) NOT NULL,
action_type varchar(50) NOT NULL,
action_value text,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY user_id (user_id),
KEY post_id (post_id),
KEY action_type (action_type)
) $charset_collate;
",
"{$wpdb->prefix}icd_performance_metrics" => "
CREATE TABLE {$wpdb->prefix}icd_performance_metrics (
id bigint(20) NOT NULL AUTO_INCREMENT,
metric_name varchar(100) NOT NULL,
metric_value float NOT NULL,
tags text,
recorded_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY metric_name (metric_name),
KEY recorded_at (recorded_at)
) $charset_collate;
"
);
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
foreach ($tables as $table_name => $sql) {
环境要求检查
- PHP 7.4+ 版本
- MySQL 5.7+ 或 MariaDB 10.3+
- WordPress 5.8+
- 至少 256MB PHP 内存限制
# 1. 创建插件目录
cd wp-content/plugins
mkdir intelligent-content-distribution
# 2. 复制所有类文件
cp *.php intelligent-content-distribution/
# 3. 创建主插件文件
cat > intelligent-content-distribution.php << 'EOF'
<?php
/**
* Plugin Name: 智能内容分发系统
* Description: WordPress柔性内容智能分发策略配置
* Version: 1.0.0
* Author: 网络传媒技术团队
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('ICD_VERSION', '1.0.0');
define('ICD_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ICD_PLUGIN_URL', plugin_dir_url(__FILE__));
// 自动加载类文件
spl_autoload_register(function ($class_name) {
$class_map = array(
'IntelligentContentDistribution' => 'class-intelligent-distribution.php',
'UserProfileAnalyzer' => 'class-user-analyzer.php',
'ContentMatchingAlgorithm' => 'class-matching-algorithm.php',
'ICD_Admin_Configuration' => 'class-admin-config.php',
'ICD_Cache_System' => 'class-cache-system.php',
'AB_Testing_Manager' => 'class-ab-testing.php',
'ICD_Monitoring_System' => 'class-monitoring.php'
);
if (isset($class_map[$class_name])) {
require_once ICD_PLUGIN_DIR . 'includes/' . $class_map[$class_name];
}
});
// 初始化插件
add_action('plugins_loaded', 'icd_initialize_plugin');
function icd_initialize_plugin() {
// 检查依赖
if (!class_exists('WP_Http')) {
require_once ABSPATH . WPINC . '/class-http.php';
}
// 初始化核心组件
$distribution_system = new IntelligentContentDistribution();
$admin_config = new ICD_Admin_Configuration();
$monitoring = new ICD_Monitoring_System();
// 注册激活/停用钩子
register_activation_hook(__FILE__, 'icd_activate_plugin');
register_deactivation_hook(__FILE__, 'icd_deactivate_plugin');
}
function icd_activate_plugin() {
// 创建数据库表
icd_create_database_tables();
// 设置默认选项
icd_set_default_options();
// 添加管理员通知
set_transient('icd_activation_notice', true, 60);
}
function icd_create_database_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$tables = array(
"{$wpdb->prefix}icd_user_behavior" => "
CREATE TABLE {$wpdb->prefix}icd_user_behavior (
id bigint(20) NOT NULL AUTO_INCREMENT,
user_id bigint(20) NOT NULL,
post_id bigint(20) NOT NULL,
action_type varchar(50) NOT NULL,
action_value text,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY user_id (user_id),
KEY post_id (post_id),
KEY action_type (action_type)
) $charset_collate;
",
"{$wpdb->prefix}icd_performance_metrics" => "
CREATE TABLE {$wpdb->prefix}icd_performance_metrics (
id bigint(20) NOT NULL AUTO_INCREMENT,
metric_name varchar(100) NOT NULL,
metric_value float NOT NULL,
tags text,
recorded_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY metric_name (metric_name),
KEY recorded_at (recorded_at)
) $charset_collate;
"
);
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
foreach ($tables as $table_name => $sql) {


