首页 / 应用软件 / WordPress开发教程,集成网站自动化社交媒体舆情监控与警报

WordPress开发教程,集成网站自动化社交媒体舆情监控与警报

WordPress开发教程:集成网站自动化社交媒体舆情监控与警报,通过WordPress程序的代码二次开发实现常用互联网小工具功能

引言:WordPress的无限可能

在当今数字化时代,网站已不仅仅是信息展示的平台,更是企业与用户互动、品牌传播和业务拓展的核心阵地。作为全球最受欢迎的内容管理系统,WordPress以其开源特性、灵活的可扩展性和庞大的开发者社区,占据了互联网超过43%的网站市场份额。然而,许多WordPress用户仅停留在使用现成主题和插件的层面,未能充分挖掘其深层潜力。

本教程将深入探讨如何通过WordPress代码二次开发,将您的网站从一个被动的内容发布平台,转变为一个集成了自动化社交媒体舆情监控与警报系统的智能工具。我们将逐步引导您实现这一复杂功能,同时在这个过程中,掌握如何通过自定义开发为WordPress添加各种实用的小工具功能,从而大幅提升网站的价值和效率。

第一部分:WordPress开发基础与环境配置

1.1 WordPress开发环境搭建

在开始任何WordPress开发项目之前,建立一个合适的开发环境至关重要。我们推荐使用本地开发环境,如Local by Flywheel、XAMPP或MAMP,这些工具可以快速在本地计算机上搭建WordPress运行所需的PHP、MySQL和Web服务器环境。

对于本教程涉及的开发工作,您需要确保环境满足以下要求:

  • PHP 7.4或更高版本(建议8.0+)
  • MySQL 5.6或更高版本或MariaDB 10.1+
  • WordPress 5.8或更高版本
  • 代码编辑器(如VS Code、PHPStorm等)
  • Git版本控制系统

1.2 子主题创建与最佳实践

为了避免直接修改主题文件导致更新时丢失自定义代码,我们始终建议使用子主题进行开发。创建子主题只需在wp-content/themes目录下新建一个文件夹,并包含以下基本文件:

  1. style.css - 子主题样式表,必须包含特定的头部信息:

    /*
    Theme Name: 我的自定义子主题
    Template: parent-theme-folder-name
    Version: 1.0.0
    */
  2. functions.php - 子主题功能文件,用于添加自定义代码:

    <?php
    // 子主题functions.php
    add_action('wp_enqueue_scripts', 'my_child_theme_scripts');
    function my_child_theme_scripts() {
     // 加载父主题样式
     wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
     // 加载子主题样式
     wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style'));
    }

1.3 WordPress钩子(Hooks)系统理解

WordPress的钩子系统是扩展其功能的核心机制,分为两种类型:

  1. 动作(Actions):在特定时刻执行自定义代码
  2. 过滤器(Filters):修改数据后再返回

理解并熟练使用钩子是高级WordPress开发的基础。例如,我们将在舆情监控系统中使用wp_cron钩子来定期执行监控任务。

第二部分:社交媒体API集成基础

2.1 社交媒体API概览与申请

要实现社交媒体舆情监控,首先需要获取各大社交平台的API访问权限。以下是主要平台的API申请要点:

  1. Twitter API(现为X平台):

    • 访问developer.twitter.com申请开发者账户
    • 创建项目和应用获取API密钥和访问令牌
    • 注意:Twitter API v2有严格的访问限制和费用结构
  2. Facebook Graph API

    • 通过Facebook开发者平台创建应用
    • 需要应用审核才能访问某些接口
    • 获取长期访问令牌以实现自动化
  3. Instagram Basic Display API

    • 只能访问用户自己的内容
    • 需要用户授权流程
    • 适用于监控品牌自己的Instagram账户
  4. YouTube Data API

    • 通过Google Cloud Console启用
    • 每日有免费配额限制
    • 可以搜索视频和评论
  5. Reddit API

    • 相对宽松的访问政策
    • 需要遵守API使用规则
    • 可以访问公开的帖子和评论

2.2 WordPress中安全存储API密钥

绝对不要在代码中硬编码API密钥。WordPress提供了安全存储敏感数据的方法:

// 在主题或插件中安全存储和获取API密钥
function save_social_api_keys() {
    if (isset($_POST['twitter_api_key'])) {
        update_option('twitter_api_key', sanitize_text_field($_POST['twitter_api_key']));
    }
}

function get_twitter_api_key() {
    return get_option('twitter_api_key', '');
}

// 或者使用更安全的wp-config.php常量定义
// define('TWITTER_API_KEY', 'your_actual_key_here');

2.3 API请求处理与错误处理

在WordPress中发起API请求时,应使用内置的HTTP函数:

function make_api_request($url, $args = array()) {
    $defaults = array(
        'timeout' => 30,
        'headers' => array(
            'Authorization' => 'Bearer ' . get_option('twitter_bearer_token')
        )
    );
    
    $args = wp_parse_args($args, $defaults);
    $response = wp_remote_get($url, $args);
    
    if (is_wp_error($response)) {
        // 记录错误日志
        error_log('API请求失败: ' . $response->get_error_message());
        return false;
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log('JSON解析错误: ' . json_last_error_msg());
        return false;
    }
    
    return $data;
}

第三部分:构建舆情监控系统核心

3.1 数据库设计与数据模型

我们需要创建自定义数据库表来存储监控到的社交媒体内容:

function create_social_monitoring_tables() {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'social_mentions';
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        platform varchar(50) NOT NULL,
        post_id varchar(255) NOT NULL,
        author_name varchar(255),
        author_username varchar(255),
        content text NOT NULL,
        url varchar(500),
        sentiment_score float DEFAULT 0,
        engagement_count int DEFAULT 0,
        mention_date datetime DEFAULT CURRENT_TIMESTAMP,
        processed tinyint(1) DEFAULT 0,
        PRIMARY KEY (id),
        UNIQUE KEY post_platform (post_id, platform),
        KEY platform_index (platform),
        KEY sentiment_index (sentiment_score),
        KEY date_index (mention_date)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
add_action('after_setup_theme', 'create_social_monitoring_tables');

3.2 多平台数据采集引擎

创建一个统一的数据采集引擎,支持多个社交平台:

class SocialMediaMonitor {
    private $platforms = array();
    
    public function __construct() {
        $this->platforms = array(
            'twitter' => new TwitterMonitor(),
            'facebook' => new FacebookMonitor(),
            // 可以轻松扩展其他平台
        );
    }
    
    public function collect_mentions($keywords, $hours = 24) {
        $all_mentions = array();
        
        foreach ($this->platforms as $platform => $monitor) {
            if ($monitor->is_enabled()) {
                $mentions = $monitor->search_mentions($keywords, $hours);
                $all_mentions = array_merge($all_mentions, $mentions);
                
                // 存储到数据库
                $this->store_mentions($mentions, $platform);
            }
        }
        
        return $all_mentions;
    }
    
    private function store_mentions($mentions, $platform) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'social_mentions';
        
        foreach ($mentions as $mention) {
            $wpdb->replace(
                $table_name,
                array(
                    'platform' => $platform,
                    'post_id' => $mention['id'],
                    'author_name' => $mention['author_name'],
                    'author_username' => $mention['author_username'],
                    'content' => $mention['content'],
                    'url' => $mention['url'],
                    'mention_date' => $mention['created_at'],
                    'engagement_count' => $mention['engagement']
                ),
                array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d')
            );
        }
    }
}

3.3 情感分析与关键词识别

集成情感分析功能,自动判断提及内容的情感倾向:

class SentimentAnalyzer {
    public function analyze($text) {
        // 使用简单的词典方法进行情感分析
        // 实际项目中可以考虑使用机器学习API如Google Natural Language API
        
        $positive_words = array('好', '优秀', '推荐', '喜欢', '满意', '棒', '赞');
        $negative_words = array('差', '糟糕', '讨厌', '失望', '垃圾', '差评', '投诉');
        
        $score = 0;
        $words = $this->segment_text($text); // 中文需要分词
        
        foreach ($words as $word) {
            if (in_array($word, $positive_words)) {
                $score += 1;
            } elseif (in_array($word, $negative_words)) {
                $score -= 1;
            }
        }
        
        // 归一化到-1到1之间
        $normalized_score = tanh($score / 10);
        
        return array(
            'score' => $normalized_score,
            'sentiment' => $this->get_sentiment_label($normalized_score)
        );
    }
    
    private function get_sentiment_label($score) {
        if ($score > 0.3) return '积极';
        if ($score < -0.3) return '消极';
        return '中性';
    }
    
    private function segment_text($text) {
        // 简单的中文分词,实际项目应使用专业分词库如jieba-php
        return preg_split('/s+/', $text);
    }
}

第四部分:实时警报系统实现

4.1 警报规则引擎设计

创建一个灵活的警报规则系统,允许用户自定义触发条件:

class AlertEngine {
    private $rules = array();
    
    public function __construct() {
        $this->load_rules();
    }
    
    public function check_mention($mention) {
        $alerts_triggered = array();
        
        foreach ($this->rules as $rule) {
            if ($this->evaluate_rule($rule, $mention)) {
                $alerts_triggered[] = $rule['id'];
                $this->trigger_alert($rule, $mention);
            }
        }
        
        return $alerts_triggered;
    }
    
    private function evaluate_rule($rule, $mention) {
        $conditions_met = 0;
        
        foreach ($rule['conditions'] as $condition) {
            if ($this->check_condition($condition, $mention)) {
                $conditions_met++;
            }
        }
        
        // 根据规则类型判断是否触发
        if ($rule['type'] === 'all' && $conditions_met === count($rule['conditions'])) {
            return true;
        } elseif ($rule['type'] === 'any' && $conditions_met > 0) {
            return true;
        }
        
        return false;
    }
    
    private function check_condition($condition, $mention) {
        switch ($condition['field']) {
            case 'sentiment':
                return $this->compare_sentiment($mention['sentiment_score'], $condition['operator'], $condition['value']);
            case 'engagement':
                return $this->compare_number($mention['engagement_count'], $condition['operator'], $condition['value']);
            case 'keyword':
                return $this->check_keyword($mention['content'], $condition['value']);
            default:
                return false;
        }
    }
}

4.2 多渠道通知系统

实现通过多种渠道发送警报通知:

class NotificationSystem {
    public function send_alert($alert_data, $channels) {
        foreach ($channels as $channel) {
            switch ($channel) {
                case 'email':
                    $this->send_email_alert($alert_data);
                    break;
                case 'slack':
                    $this->send_slack_alert($alert_data);
                    break;
                case 'webhook':
                    $this->send_webhook_alert($alert_data);
                    break;
                case 'sms':
                    $this->send_sms_alert($alert_data);
                    break;
            }
        }
    }
    
    private function send_email_alert($alert_data) {
        $to = get_option('alert_email_recipient', get_option('admin_email'));
        $subject = '社交媒体警报: ' . $alert_data['title'];
        
        $message = $this->build_email_template($alert_data);
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        wp_mail($to, $subject, $message, $headers);
    }
    
    private function send_slack_alert($alert_data) {
        $webhook_url = get_option('slack_webhook_url');
        
        if (!$webhook_url) return;
        
        $payload = array(
            'text' => $alert_data['title'],
            'blocks' => array(
                array(
                    'type' => 'section',
                    'text' => array(
                        'type' => 'mrkdwn',
                        'text' => "*新警报:* " . $alert_data['title']
                    )
                ),
                array(
                    'type' => 'section',
                    'text' => array(
                        'type' => 'mrkdwn',
                        'text' => $alert_data['content']
                    )
                )
            )
        );
        
        wp_remote_post($webhook_url, array(
            'body' => json_encode($payload),
            'headers' => array('Content-Type' => 'application/json')
        ));
    }
}

4.3 WordPress Cron定时任务集成

使用WordPress内置的Cron系统定期执行监控任务:

class MonitoringScheduler {
    public function __construct() {
        add_action('social_monitoring_cron', array($this, 'run_monitoring'));
        add_filter('cron_schedules', array($this, 'add_custom_schedules'));
    }
    
    public function activate() {
        if (!wp_next_scheduled('social_monitoring_cron')) {
            wp_schedule_event(time(), 'every_15_minutes', 'social_monitoring_cron');
        }
    }
    
    public function deactivate() {
        wp_clear_scheduled_hook('social_monitoring_cron');
    }
    
    public function add_custom_schedules($schedules) {
        $schedules['every_15_minutes'] = array(
            'interval' => 15 * 60,
            'display' => __('每15分钟')
        );
        
        $schedules['every_hour'] = array(
            'interval' => 60 * 60,
            'display' => __('每小时')
        );
        
        return $schedules;
    }
    
    public function run_monitoring() {
        $monitor = new SocialMediaMonitor();
        $keywords = get_option('monitoring_keywords', array());
        
        if (empty($keywords)) {
            error_log('未设置监控关键词');
            return;
        }
        
        $mentions = $monitor->collect_mentions($keywords, 1); // 监控最近1小时的内容
        
        $alert_engine = new AlertEngine();
        foreach ($mentions as $mention) {
            $alert_engine->check_mention($mention);
        }
        
        // 记录执行日志
        $this->log_execution(count($mentions));
    }
}

第五部分:管理界面与可视化仪表板

5.1 WordPress管理菜单集成

创建用户友好的管理界面:

class MonitoringAdmin {
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    }
    
    public function add_admin_menu() {
        add_menu_page(
            '社交媒体监控',
            '社媒监控',
            'manage_options',
            'social-monitoring',
            array($this, 'render_dashboard'),
            'dashicons-share',
            30
        );
        
        add_submenu_page(
            'social-monitoring',
            '监控仪表板',
            '仪表板',
            'manage_options',
            'social-monitoring',
            array($this, 'render_dashboard')
        );
        
        add_submenu_page(
            'social-monitoring',
            '警报规则',
            '警报规则',
            'manage_options',
            'social-monitoring-rules',
            array($this, 'render_rules_page')
        );
        
        add_submenu_page(
            'social-monitoring',
            '设置',
            '设置',
            'manage_options',
            'social-monitoring-settings',
            array($this, 'render_settings_page')
        );
    }
    
    public function render_dashboard() {
        include plugin_dir_path(__FILE__) . 'templates/dashboard.php';
    }
}

5.2 数据可视化与图表

使用Chart.js或ECharts创建交互式数据可视化:

public function enqueue_admin_scripts($hook) {
    if (strpos($hook, 'social-monitoring') === false) {
        return;
    }
    
    // 加载Chart.js
    wp_enqueue_script(
        'chart-js',
        'https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js',
        array(),
        '3.7.0',
        true
    );
    
    // 加载自定义仪表板脚本
    wp_enqueue_script(
        'monitoring-dashboard',
        plugin_dir_url(__FILE__) . 'js/dashboard.js',
        array('jquery', 'chart-js'),
        '1.0.0',
);

// 传递数据到前端
wp_localize_script('monitoring-dashboard', 'monitoringData', array(
    'sentimentData' => $this->get_sentiment_chart_data(),
    'platformData' => $this->get_platform_distribution_data(),
    'timelineData' => $this->get_mentions_timeline_data()
));

}

private function get_sentiment_chart_data() {

global $wpdb;
$table_name = $wpdb->prefix . 'social_mentions';

$results = $wpdb->get_results("
    SELECT 
        CASE 
            WHEN sentiment_score > 0.3 THEN '积极'
            WHEN sentiment_score < -0.3 THEN '消极'
            ELSE '中性'
        END as sentiment,
        COUNT(*) as count
    FROM $table_name
    WHERE mention_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY 
        CASE 
            WHEN sentiment_score > 0.3 THEN '积极'
            WHEN sentiment_score < -0.3 THEN '消极'
            ELSE '中性'
        END
");

$data = array(
    'labels' => array('积极', '中性', '消极'),
    'datasets' => array(
        array(
            'data' => array(0, 0, 0),
            'backgroundColor' => array('#4CAF50', '#2196F3', '#F44336')
        )
    )
);

foreach ($results as $row) {
    $index = array_search($row->sentiment, $data['labels']);
    if ($index !== false) {
        $data['datasets'][0]['data'][$index] = (int)$row->count;
    }
}

return $data;

}


#### 5.3 实时数据更新与AJAX集成

实现无需刷新页面的实时数据更新:

class RealTimeUpdater {

public function __construct() {
    add_action('wp_ajax_get_recent_mentions', array($this, 'ajax_get_recent_mentions'));
    add_action('wp_ajax_nopriv_get_recent_mentions', array($this, 'ajax_no_permission'));
    add_action('wp_ajax_update_alert_status', array($this, 'ajax_update_alert_status'));
}

public function ajax_get_recent_mentions() {
    // 验证nonce
    if (!wp_verify_nonce($_POST['nonce'], 'monitoring_ajax_nonce')) {
        wp_die('权限验证失败');
    }
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'social_mentions';
    
    $limit = intval($_POST['limit'] ?? 10);
    $offset = intval($_POST['offset'] ?? 0);
    
    $mentions = $wpdb->get_results($wpdb->prepare("
        SELECT * FROM $table_name
        ORDER BY mention_date DESC
        LIMIT %d OFFSET %d
    ", $limit, $offset));
    
    // 格式化数据
    $formatted_mentions = array();
    foreach ($mentions as $mention) {
        $formatted_mentions[] = array(
            'id' => $mention->id,
            'platform' => $mention->platform,
            'author' => $mention->author_name ?: $mention->author_username,
            'content' => wp_trim_words($mention->content, 20),
            'sentiment' => $this->get_sentiment_label($mention->sentiment_score),
            'sentiment_score' => $mention->sentiment_score,
            'engagement' => $mention->engagement_count,
            'time' => human_time_diff(strtotime($mention->mention_date), current_time('timestamp')),
            'url' => $mention->url
        );
    }
    
    wp_send_json_success(array(
        'mentions' => $formatted_mentions,
        'total' => $wpdb->get_var("SELECT COUNT(*) FROM $table_name")
    ));
}

public function ajax_update_alert_status() {
    if (!current_user_can('manage_options')) {
        wp_send_json_error('权限不足');
    }
    
    $alert_id = intval($_POST['alert_id']);
    $status = sanitize_text_field($_POST['status']);
    
    // 更新警报状态逻辑
    $result = $this->update_alert_in_database($alert_id, $status);
    
    if ($result) {
        wp_send_json_success('状态更新成功');
    } else {
        wp_send_json_error('更新失败');
    }
}

}


### 第六部分:实用小工具功能扩展

#### 6.1 短代码(Shortcode)系统开发

创建灵活的短代码系统,让用户可以在文章或页面中嵌入监控数据:

class MonitoringShortcodes {

public function __construct() {
    add_shortcode('social_mentions', array($this, 'render_mentions_shortcode'));
    add_shortcode('sentiment_chart', array($this, 'render_sentiment_chart'));
    add_shortcode('top_influencers', array($this, 'render_influencers_list'));
}

public function render_mentions_shortcode($atts) {
    $atts = shortcode_atts(array(
        'limit' => 5,
        'platform' => 'all',
        'sentiment' => 'all',
        'days' => 7
    ), $atts);
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'social_mentions';
    
    $where_clauses = array("mention_date >= DATE_SUB(NOW(), INTERVAL %d DAY)");
    $where_values = array(intval($atts['days']));
    
    if ($atts['platform'] !== 'all') {
        $where_clauses[] = "platform = %s";
        $where_values[] = sanitize_text_field($atts['platform']);
    }
    
    if ($atts['sentiment'] !== 'all') {
        $sentiment_map = array(
            'positive' => 'sentiment_score > 0.3',
            'negative' => 'sentiment_score < -0.3',
            'neutral' => 'sentiment_score BETWEEN -0.3 AND 0.3'
        );
        
        if (isset($sentiment_map[$atts['sentiment']])) {
            $where_clauses[] = $sentiment_map[$atts['sentiment']];
        }
    }
    
    $where_sql = implode(' AND ', $where_clauses);
    
    $mentions = $wpdb->get_results($wpdb->prepare("
        SELECT * FROM $table_name
        WHERE $where_sql
        ORDER BY engagement_count DESC
        LIMIT %d
    ", array_merge($where_values, array(intval($atts['limit'])))));
    
    ob_start();
    ?>
    <div class="social-mentions-widget">
        <h3>最新社交媒体提及</h3>
        <div class="mentions-list">
            <?php foreach ($mentions as $mention): ?>
            <div class="mention-item">
                <div class="mention-platform platform-<?php echo esc_attr($mention->platform); ?>">
                    <?php echo esc_html(ucfirst($mention->platform)); ?>
                </div>
                <div class="mention-content">
                    <?php echo esc_html(wp_trim_words($mention->content, 15)); ?>
                </div>
                <div class="mention-meta">
                    <span class="mention-author">@<?php echo esc_html($mention->author_username); ?></span>
                    <span class="mention-time"><?php echo human_time_diff(strtotime($mention->mention_date), current_time('timestamp')); ?>前</span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <style>
        .social-mentions-widget { border: 1px solid #ddd; padding: 15px; border-radius: 5px; }
        .mention-item { border-bottom: 1px solid #eee; padding: 10px 0; }
        .mention-platform { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 12px; color: white; }
        .platform-twitter { background: #1DA1F2; }
        .platform-facebook { background: #4267B2; }
        .mention-meta { font-size: 12px; color: #666; margin-top: 5px; }
    </style>
    <?php
    return ob_get_clean();
}

}


#### 6.2 WordPress小工具(Widget)开发

创建可拖拽的侧边栏小工具:

class SocialMonitoringWidget extends WP_Widget {

public function __construct() {
    parent::__construct(
        'social_monitoring_widget',
        '社交媒体监控',
        array('description' => '显示最新的社交媒体提及和情感分析')
    );
}

public function widget($args, $instance) {
    echo $args['before_widget'];
    
    $title = apply_filters('widget_title', $instance['title']);
    if (!empty($title)) {
        echo $args['before_title'] . $title . $args['after_title'];
    }
    
    // 获取数据
    $data = $this->get_widget_data($instance);
    
    // 渲染小工具内容
    $this->render_widget_content($data, $instance);
    
    echo $args['after_widget'];
}

public function form($instance) {
    $title = $instance['title'] ?? '社交媒体监控';
    $limit = $instance['limit'] ?? 5;
    $show_chart = $instance['show_chart'] ?? true;
    ?>
    <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('limit'); ?>">显示数量:</label>
        <input class="tiny-text" id="<?php echo $this->get_field_id('limit'); ?>"
               name="<?php echo $this->get_field_name('limit'); ?>"
               type="number" value="<?php echo esc_attr($limit); ?>" min="1" max="20">
    </p>
    <p>
        <input class="checkbox" type="checkbox"
               id="<?php echo $this->get_field_id('show_chart'); ?>"
               name="<?php echo $this->get_field_name('show_chart'); ?>"
               <?php checked($show_chart); ?>>
        <label for="<?php echo $this->get_field_id('show_chart'); ?>">显示情感图表</label>
    </p>
    <?php
}

public function update($new_instance, $old_instance) {
    $instance = array();
    $instance['title'] = sanitize_text_field($new_instance['title'] ?? '');
    $instance['limit'] = intval($new_instance['limit'] ?? 5);
    $instance['show_chart'] = isset($new_instance['show_chart']);
    return $instance;
}

}

// 注册小工具
add_action('widgets_init', function() {

register_widget('SocialMonitoringWidget');

});


#### 6.3 REST API端点创建

为监控系统创建REST API,支持与其他系统集成:

class MonitoringRESTAPI {

public function __construct() {
    add_action('rest_api_init', array($this, 'register_routes'));
}

public function register_routes() {
    register_rest_route('social-monitoring/v1', '/mentions', array(
        array(
            'methods' => WP_REST_Server::READABLE,
            'callback' => array($this, 'get_mentions'),
            'permission_callback' => array($this, 'check_api_permission'),
            'args' => $this->get_mentions_args()
        ),
        array(
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => array($this, 'create_mention'),
            'permission_callback' => array($this, 'check_api_permission')
        )
    ));
    
    register_rest_route('social-monitoring/v1', '/analytics', array(
        'methods' => WP_REST_Server::READABLE,
        'callback' => array($this, 'get_analytics'),
        'permission_callback' => array($this, 'check_api_permission')
    ));
    
    register_rest_route('social-monitoring/v1', '/alerts', array(
        'methods' => WP_REST_Server::READABLE,
        'callback' => array($this, 'get_alerts'),
        'permission_callback' => array($this, 'check_api_permission')
    ));
}

public function get_mentions(WP_REST_Request $request) {
    $params = $request->get_params();
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'social_mentions';
    
    $page = max(1, intval($params['page'] ?? 1));
    $per_page = min(100, intval($params['per_page'] ?? 20));
    $offset = ($page - 1) * $per_page;
    
    // 构建查询条件
    $where = array('1=1');
    $query_params = array();
    
    if (!empty($params['platform'])) {
        $where[] = 'platform = %s';
        $query_params[] = sanitize_text_field($params['platform']);
    }
    
    if (!empty($params['start_date'])) {
        $where[] = 'mention_date >= %s';
        $query_params[] = sanitize_text_field($params['start_date']);
    }
    
    if (!empty($params['end_date'])) {
        $where[] = 'mention_date <= %s';
        $query_params[] = sanitize_text_field($params['end_date']);
    }
    
    if (!empty($params['sentiment'])) {
        if ($params['sentiment'] === 'positive') {
            $where[] = 'sentiment_score > 0.3';
        } elseif ($params['sentiment'] === 'negative') {
            $where[] = 'sentiment_score < -0.3';
        } else {
            $where[] = 'sentiment_score BETWEEN -0.3 AND 0.3';
        }
    }
    
    $where_sql = implode(' AND ', $where);
    
    // 获取总数
    $count_query = "SELECT COUNT(*) FROM $table_name WHERE $where_sql";
    if (!empty($query_params)) {
        $count_query = $wpdb->prepare($count_query, $query_params);
    }
    $total = $wpdb->get_var($count_query);
    
    // 获取数据
    $data_query = "SELECT * FROM $table_name WHERE $where_sql ORDER BY mention_date DESC LIMIT %d OFFSET %d";
    $query_params[] = $per_page;
    $query_params[] = $offset;
    
    $data = $wpdb->get_results($wpdb->prepare($data_query, $query_params));
    
    // 格式化响应
    $formatted_data = array();
    foreach ($data as $item) {
        $formatted_data[] = array(
            'id' => $item->id,
            'platform' => $item->platform,
            'author' => array(
                'name' => $item->author_name,
                'username' => $item->author_username
            ),
            'content' => $item->content,
            'url' => $item->url,
            'sentiment' => array(
                'score' => floatval($item->sentiment_score),
                'label' => $this->get_sentiment_label(floatval($item->sentiment_score))
            ),
            'engagement' => intval($item->engagement_count),
            'date' => $item->mention_date
        );
    }
    
    return new WP_REST_Response(array(
        'data' => $formatted_data,
        'pagination' => array(
            'page' => $page,
            'per_page' => $per_page,
            'total' => intval($total),
            'total_pages' => ceil($total / $per_page)
        )
    ), 200);
}

}


### 第七部分:性能优化与安全加固

#### 7.1 数据库查询优化

优化监控系统的数据库性能:

class DatabaseOptimizer {

public function optimize_tables() {
    global $wpdb;
    
    // 定期清理旧数据
    $retention_days = get_option('data_retention_days', 90);
    $table_name = $wpdb->prefix . 'social_mentions';
    
    $wpdb->query($wpdb->prepare("
        DELETE FROM $table_name 
        WHERE mention_date < DATE_SUB(NOW(), INTERVAL %d DAY)
    ", $retention_days));
    
    // 优化表
    $wpdb->query("OPTIMIZE TABLE $table_name");
    
    // 创建和维护索引
    $this->maintain_indexes();
}

private function maintain_indexes() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'social_mentions';
    
    // 检查并添加缺失的索引
    $indexes = $wpdb->get_results("SHOW INDEX FROM $table_name");
    $existing_indexes = array();
    
    foreach ($indexes as $index) {
        $existing_indexes[] = $index->Key_name;
    }
    
    // 添加常用查询的复合索引
    if (!in_array('idx_platform_date', $existing_indexes)) {
        $wpdb->query("CREATE INDEX idx_platform_date ON $table_name (platform, mention_date)");
    }
    
    if (!in_array('idx_sentiment_engagement', $existing_indexes)) {
        $wpdb->query("CREATE INDEX idx_sentiment_engagement ON $table_name (sentiment_score, engagement_count)");
    }
}

public function add_query_cache() {
    // 使用WordPress瞬
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5230.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部