首页 / 教程文章 / 网络传媒WordPress站点柔性内容智能标签与分类插件应用教程

网络传媒WordPress站点柔性内容智能标签与分类插件应用教程

本文针对WordPress站点面临的海量内容管理挑战,介绍了柔性内容智能标签与分类插件的应用。这类插件利用人工智能技术,自动分析内容语义,智能生成标签与分类建议,从而提升管理效率与准确性。教程以“AI Content Tagger”插件为例,详细讲解了从选择安装、基础配置(如API密钥设置)到核心功能(自动标签生成、分类建议)的实现步骤。此外,还涵盖了自定义标签规则、批量处理现有内容等高级功能,并提供了缓存系统、异步处理及性能监控的代码示例,助力媒体站点实现高效、智能的内容组织。

WordPress站点柔性内容智能标签与分类插件应用教程

引言:内容管理的新挑战与解决方案

在当今信息爆炸的时代,网络传媒站点面临着海量内容管理的巨大挑战。传统的内容分类和标签管理方式已难以满足高效、精准的内容组织需求。WordPress作为全球最流行的内容管理系统,虽然提供了基础的分类和标签功能,但对于需要处理大量内容、追求智能分类的媒体站点来说,这些基础功能显得力不从心。

柔性内容智能标签与分类插件应运而生,它通过人工智能技术,自动分析内容语义,智能生成标签和分类建议,大大提升了内容管理的效率和准确性。本教程将详细介绍如何应用这类插件,并附上完整的代码示例。

插件选择与安装

选择合适的智能标签插件

目前WordPress生态中有多款优秀的智能标签插件,如:

  • Auto Tagging Plugin:基于自然语言处理的自动标签生成
  • Smart Content Filter:提供智能分类和标签建议
  • AI Content Tagger:使用机器学习算法分析内容

本教程将以"AI Content Tagger"为例进行演示,该插件功能全面且支持自定义开发。

安装与激活插件

  1. 登录WordPress后台,进入"插件"→"安装插件"
  2. 搜索"AI Content Tagger"
  3. 点击"立即安装",然后激活插件
  4. 或者,您也可以下载插件ZIP文件,通过上传方式安装

基础配置与设置

初始配置步骤

激活插件后,需要进行基础配置:

/**
 * AI Content Tagger 基础配置示例
 * 这段代码展示了如何通过函数配置插件基础设置
 */

function setup_ai_content_tagger_basic_config() {
    // 检查插件是否激活
    if (!function_exists('ai_tagger_init')) {
        return;
    }
    
    // 设置基础选项
    $options = array(
        'auto_tagging' => true,           // 启用自动标签
        'min_confidence' => 0.7,          // 最小置信度阈值
        'max_tags' => 10,                 // 最大标签数量
        'exclude_words' => 'the,and,or',  // 排除的常见词
        'language' => 'zh_CN',            // 分析语言
    );
    
    // 更新插件选项
    update_option('ai_tagger_settings', $options);
    
    // 启用分类建议功能
    update_option('ai_tagger_enable_categorization', true);
    
    // 设置分类模型(预训练或自定义)
    update_option('ai_tagger_category_model', 'pre_trained_zh');
}
add_action('admin_init', 'setup_ai_content_tagger_basic_config');

API密钥配置(如使用云端AI服务)

如果插件使用云端AI服务(如Google Natural Language API或百度NLP),需要配置API密钥:

/**
 * 配置AI服务API密钥
 * 注意:实际密钥应从安全配置中获取,不应硬编码在代码中
 */

function configure_ai_service_api() {
    // 从环境变量或安全存储获取API密钥
    $api_key = defined('AI_SERVICE_API_KEY') ? AI_SERVICE_API_KEY : '';
    
    if (empty($api_key)) {
        // 记录错误日志
        error_log('AI服务API密钥未配置');
        return;
    }
    
    // 配置API端点(示例为Google Natural Language API)
    $api_config = array(
        'api_key' => $api_key,
        'endpoint' => 'https://language.googleapis.com/v1/documents:analyzeEntities',
        'timeout' => 30, // 请求超时时间(秒)
        'retry_attempts' => 3, // 重试次数
    );
    
    // 保存配置
    update_option('ai_tagger_api_config', $api_config);
    
    // 测试API连接
    test_ai_api_connection($api_config);
}

/**
 * 测试API连接
 */
function test_ai_api_connection($config) {
    $test_data = array(
        'document' => array(
            'type' => 'PLAIN_TEXT',
            'content' => '测试连接'
        ),
        'encodingType' => 'UTF8'
    );
    
    $response = wp_remote_post(
        $config['endpoint'] . '?key=' . $config['api_key'],
        array(
            'body' => json_encode($test_data),
            'headers' => array('Content-Type' => 'application/json'),
            'timeout' => $config['timeout']
        )
    );
    
    if (is_wp_error($response)) {
        error_log('AI API连接测试失败: ' . $response->get_error_message());
    } else {
        error_log('AI API连接测试成功');
    }
}
add_action('admin_init', 'configure_ai_service_api');

核心功能实现

自动标签生成功能

智能标签插件的核心功能是自动分析文章内容并生成相关标签:

/**
 * 自动标签生成函数
 * 分析文章内容并生成智能标签
 */

function generate_auto_tags($post_id) {
    // 获取文章内容
    $post = get_post($post_id);
    if (!$post) {
        return false;
    }
    
    // 提取文本内容(去除HTML标签)
    $content = strip_tags($post->post_content);
    $title = strip_tags($post->post_title);
    
    // 合并标题和内容进行分析
    $text_to_analyze = $title . ' ' . $content;
    
    // 如果内容太短,返回空结果
    if (strlen($text_to_analyze) < 50) {
        return array();
    }
    
    // 调用AI分析函数
    $analysis_result = analyze_text_with_ai($text_to_analyze);
    
    if (!$analysis_result || empty($analysis_result['entities'])) {
        return array();
    }
    
    // 处理分析结果,提取标签
    $tags = process_ai_analysis($analysis_result);
    
    // 将标签应用到文章
    apply_tags_to_post($post_id, $tags);
    
    return $tags;
}

/**
 * 处理AI分析结果
 */
function process_ai_analysis($analysis_result) {
    $tags = array();
    $min_confidence = get_option('ai_tagger_min_confidence', 0.7);
    $max_tags = get_option('ai_tagger_max_tags', 10);
    
    // 按置信度排序
    usort($analysis_result['entities'], function($a, $b) {
        return $b['confidence'] <=> $a['confidence'];
    });
    
    // 提取符合条件的实体作为标签
    foreach ($analysis_result['entities'] as $entity) {
        if ($entity['confidence'] >= $min_confidence && count($tags) < $max_tags) {
            // 清洗标签文本
            $tag_name = clean_tag_name($entity['name']);
            
            // 排除常见词
            if (!is_common_word($tag_name)) {
                $tags[] = $tag_name;
            }
        }
    }
    
    return $tags;
}

/**
 * 将标签应用到文章
 */
function apply_tags_to_post($post_id, $tags) {
    if (empty($tags)) {
        return;
    }
    
    // 确保标签存在,不存在则创建
    $tag_ids = array();
    foreach ($tags as $tag) {
        $term = term_exists($tag, 'post_tag');
        if (!$term) {
            $term = wp_insert_term($tag, 'post_tag');
        }
        
        if (!is_wp_error($term) && isset($term['term_id'])) {
            $tag_ids[] = (int)$term['term_id'];
        }
    }
    
    // 设置文章标签
    if (!empty($tag_ids)) {
        wp_set_post_terms($post_id, $tag_ids, 'post_tag', true);
    }
}

// 在保存文章时触发自动标签生成
add_action('save_post', 'generate_auto_tags', 10, 1);

智能分类建议功能

除了标签生成,智能分类建议也是重要功能:

/**
 * 智能分类建议功能
 * 根据内容自动推荐分类
 */

function suggest_categories_for_post($post_id) {
    $post = get_post($post_id);
    if (!$post) {
        return array();
    }
    
    // 获取文章内容
    $content = strip_tags($post->post_content);
    
    // 获取现有分类作为训练参考
    $existing_categories = get_categories(array('hide_empty' => false));
    $category_keywords = array();
    
    // 构建分类关键词库(实际应用中应从历史数据训练)
    foreach ($existing_categories as $cat) {
        // 这里简化处理,实际应分析该分类下的文章提取关键词
        $category_keywords[$cat->term_id] = extract_keywords_from_category($cat->term_id);
    }
    
    // 分析文章内容关键词
    $content_keywords = extract_keywords_from_text($content);
    
    // 计算与每个分类的匹配度
    $category_scores = array();
    foreach ($category_keywords as $cat_id => $keywords) {
        $score = calculate_similarity($content_keywords, $keywords);
        $category_scores[$cat_id] = $score;
    }
    
    // 按匹配度排序
    arsort($category_scores);
    
    // 返回前3个建议分类
    $suggestions = array_slice($category_scores, 0, 3, true);
    
    // 保存建议到文章元数据
    update_post_meta($post_id, '_suggested_categories', $suggestions);
    
    return $suggestions;
}

/**
 * 从分类中提取关键词(简化示例)
 */
function extract_keywords_from_category($category_id) {
    // 实际应用中应分析该分类下的多篇文章
    // 这里返回模拟数据
    $category_keywords = array(
        1 => array('新闻', '报道', '时事', '政治'), // 新闻分类
        2 => array('技术', '开发', '编程', '代码'), // 技术分类
        3 => array('娱乐', '明星', '电影', '音乐'), // 娱乐分类
    );
    
    return isset($category_keywords[$category_id]) ? $category_keywords[$category_id] : array();
}

/**
 * 从文本中提取关键词
 */
function extract_keywords_from_text($text) {
    // 使用简单的分词和词频统计(实际应用应使用更复杂的方法)
    $words = str_word_count($text, 1, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
    $word_freq = array_count_values($words);
    
    // 过滤常见词
    $common_words = array('的', '了', '在', '是', '和', '与');
    foreach ($common_words as $common) {
        unset($word_freq[$common]);
    }
    
    // 按频率排序并返回前20个
    arsort($word_freq);
    return array_slice(array_keys($word_freq), 0, 20);
}

/**
 * 计算相似度(简化示例)
 */
function calculate_similarity($keywords1, $keywords2) {
    $intersection = array_intersect($keywords1, $keywords2);
    $union = array_unique(array_merge($keywords1, $keywords2));
    
    if (empty($union)) {
        return 0;
    }
    
    return count($intersection) / count($union);
}

高级功能与自定义开发

自定义标签规则

对于特定类型的媒体站点,可能需要自定义标签规则:

/**
 * 自定义标签规则系统
 * 允许根据特定规则创建标签
 */

class CustomTaggingRules {
    private $rules = array();
    
    public function __construct() {
        $this->load_rules();
    }
    
    /**
     * 加载自定义规则
     */
    private function load_rules() {
        // 示例规则:基于关键词的标签规则
        $this->rules = array(
            array(
                'name' => '技术相关',
                'keywords' => array('WordPress', 'PHP', 'JavaScript', '开发', '编程'),
                'tag' => '技术文章'
            ),
            array(
                'name' => '新闻时效性',
                'condition' => 'within_24_hours',
                'tag' => '最新消息'
            ),
            array(
                'name' => '长内容',
                'condition' => 'content_length',
                'threshold' => 2000,
                'tag' => '深度分析'
            )
        );
    }
    
    /**
     * 应用规则到文章
     */
    public function apply_rules_to_post($post_id) {
        $post = get_post($post_id);
        $content = $post->post_content;
        $created_time = strtotime($post->post_date);
        
        $applied_tags = array();
        
        foreach ($this->rules as $rule) {
            if ($this->check_rule($rule, $content, $created_time)) {
                $applied_tags[] = $rule['tag'];
            }
        }
        
        // 应用自定义规则生成的标签
        if (!empty($applied_tags)) {
            $this->add_custom_tags($post_id, $applied_tags);
        }
        
        return $applied_tags;
    }
    
    /**
     * 检查规则条件
     */
    private function check_rule($rule, $content, $created_time) {
        // 关键词规则
        if (isset($rule['keywords'])) {
            foreach ($rule['keywords'] as $keyword) {
                if (stripos($content, $keyword) !== false) {
                    return true;
                }
            }
        }
        
        // 时间条件规则
        if (isset($rule['condition']) && $rule['condition'] === 'within_24_hours') {
            $current_time = time();
            if (($current_time - $created_time) < 86400) { // 24小时内
                return true;
            }
        }
        
        // 内容长度规则
        if (isset($rule['condition']) && $rule['condition'] === 'content_length') {
            $content_length = strlen(strip_tags($content));
            if ($content_length > $rule['threshold']) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 添加自定义标签
     */
    private function add_custom_tags($post_id, $tags) {
        foreach ($tags as $tag) {
            $term = term_exists($tag, 'post_tag');
            if (!$term) {
                $term = wp_insert_term($tag, 'post_tag');
            }
            
            if (!is_wp_error($term) && isset($term['term_id'])) {
                wp_set_post_terms($post_id, array((int)$term['term_id']), 'post_tag', true);
            }
        }
    }
}

// 使用自定义规则
$custom_tagger = new CustomTaggingRules();
add_action('save_post', array($custom_tagger, 'apply_rules_to_post'), 15, 1);

批量处理现有内容

对于已有大量内容的站点,批量处理功能至关重要:

/**
 * 批量处理现有文章的标签
 */

function batch_retroactive_tagging($limit = 50) {
    // 获取未处理或需要重新处理的文章
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $limit,
        'meta_query' => array(
            array(
                'key' => '_ai_tagged',
                'compare' => 'NOT EXISTS'
            )
        )
    );
    
    $posts = get_posts($args);
    $results = array(
        'total' => count($posts),
        'processed' => 0,
        'errors' => array()
    );
    
    foreach ($posts as $post) {
        try {
            // 生成智能标签
            $tags = generate_auto_tags($post->ID);
            
            // 生成分类建议
            $categories = suggest_categories_for_post($post->ID);
            
            // 标记为已处理
            update_post_meta($post->ID, '_ai_tagged', current_time('mysql'));
            
            $results['processed']++;
            
        } catch (Exception $e) {
            $results['errors'][] = "文章ID {$post->ID} 处理失败: " . $e->getMessage();
        }
    }
    
    return $results;
}

/**
 * 提供批量处理的Admin界面
 */
function add_batch_processing_page() {
    add_submenu_page(
        'tools.php',
        '批量智能标签处理',
        '智能标签批量处理',
        'manage_options',
        'batch-ai-tagging',
        'render_batch_processing_page'
    );
}
add_action('admin_menu', 'add_batch_processing_page');

function render_batch_processing_page() {
    ?>
    <div class="wrap">
        <h1>批量智能标签处理</h1>
        
        <?php
        // 处理批量操作请求
        if (isset($_POST['start_batch']) && check_admin_referer('batch_ai_tagging')) {
            $limit = intval($_POST['batch_size']) ?: 50;
            $results = batch_retroactive_tagging($limit);
            
            echo '<div class="notice notice-success">';
            echo '<p>批量处理完成!</p>';
            echo '<ul>';
            echo '<li>总文章数: ' . $results['total'] . '</li>';
            echo '<li>成功处理: ' . $results['processed'] . '</li>';
            echo '<li>失败数: ' . count($results['errors']) . '</li>';
            echo '</ul>';
            
            if (!empty($results['errors'])) {
                echo '<h3>错误详情:</h3>';
                echo '<ul>';
                foreach ($results['errors'] as $error) {
                    echo '<li>' . esc_html($error) . '</li>';
                }
                echo '</ul>';
            }
            echo '</div>';
        }
        ?>
        
        <form method="post">
            <?php wp_nonce_field('batch_ai_tagging'); ?>
            <table class="form-table">
                <tr>
                    <th scope="row">每批处理数量</th>
                    <td>
                        <input type="number" name="batch_size" value="50" min="1" max="500">

<p class="description">设置每次处理多少篇文章(建议不超过100篇)</p>

                </td>
            </tr>
            <tr>
                <th scope="row">处理选项</th>
                <td>
                    <label>
                        <input type="checkbox" name="include_tagging" value="1" checked> 生成智能标签
                    </label><br>
                    <label>
                        <input type="checkbox" name="include_categorization" value="1" checked> 生成分类建议
                    </label><br>
                    <label>
                        <input type="checkbox" name="override_existing" value="1"> 覆盖现有标签
                    </label>
                </td>
            </tr>
        </table>
        
        <p class="submit">
            <input type="submit" name="start_batch" class="button button-primary" value="开始批量处理">
            <span class="description">处理时间取决于文章数量和内容长度</span>
        </p>
    </form>
    
    <div class="card">
        <h3>批量处理统计</h3>
        <?php
        // 显示统计信息
        $total_posts = wp_count_posts()->publish;
        $tagged_posts = new WP_Query(array(
            'meta_key' => '_ai_tagged',
            'posts_per_page' => 1,
            'fields' => 'ids'
        ));
        $tagged_count = $tagged_posts->found_posts;
        ?>
        <ul>
            <li>总文章数: <?php echo $total_posts; ?></li>
            <li>已智能标签文章数: <?php echo $tagged_count; ?></li>
            <li>待处理文章数: <?php echo $total_posts - $tagged_count; ?></li>
        </ul>
    </div>
</div>
<?php

}


## 性能优化与最佳实践

### 缓存策略实现

智能内容分析可能消耗较多资源,合理的缓存策略至关重要:

/**

  • 智能标签缓存系统
  • 缓存分析结果以提高性能
    */

class AITaggingCache {

private $cache_group = 'ai_tagging';
private $cache_expiration = 86400; // 24小时

/**
 * 获取缓存的分析结果
 */
public function get_cached_analysis($content_hash) {
    $cached = wp_cache_get($content_hash, $this->cache_group);
    
    if ($cached !== false) {
        // 检查缓存是否过期
        if (time() - $cached['timestamp'] < $this->cache_expiration) {
            return $cached['data'];
        }
    }
    
    return false;
}

/**
 * 设置缓存
 */
public function set_cached_analysis($content_hash, $analysis_data) {
    $cache_data = array(
        'data' => $analysis_data,
        'timestamp' => time()
    );
    
    wp_cache_set($content_hash, $cache_data, $this->cache_group, $this->cache_expiration);
}

/**
 * 生成内容哈希(用于缓存键)
 */
public function generate_content_hash($content) {
    // 清理内容并生成哈希
    $clean_content = preg_replace('/s+/', ' ', trim(strip_tags($content)));
    return md5($clean_content);
}

/**
 * 带缓存的智能分析
 */
public function analyze_with_cache($content) {
    $content_hash = $this->generate_content_hash($content);
    
    // 尝试从缓存获取
    $cached_result = $this->get_cached_analysis($content_hash);
    if ($cached_result !== false) {
        return $cached_result;
    }
    
    // 缓存未命中,执行实际分析
    $analysis_result = $this->perform_ai_analysis($content);
    
    // 保存到缓存
    $this->set_cached_analysis($content_hash, $analysis_result);
    
    return $analysis_result;
}

/**
 * 执行实际的AI分析
 */
private function perform_ai_analysis($content) {
    // 这里调用实际的AI分析服务
    // 示例:使用本地关键词提取作为后备方案
    
    $keywords = $this->extract_keywords_locally($content);
    $entities = array();
    
    foreach ($keywords as $keyword => $frequency) {
        $entities[] = array(
            'name' => $keyword,
            'type' => 'KEYWORD',
            'confidence' => min(0.7 + ($frequency * 0.05), 0.95) // 基于频率的置信度
        );
    }
    
    return array(
        'entities' => $entities,
        'language' => 'zh',
        'processed_at' => current_time('mysql')
    );
}

/**
 * 本地关键词提取(后备方案)
 */
private function extract_keywords_locally($content, $limit = 15) {
    // 中文分词函数(简化版,实际应使用分词库)
    function chinese_segmentation($text) {
        // 这里使用简单按字符分割,实际应用应使用jieba等分词库
        preg_match_all('/[x{4e00}-x{9fa5}]+/u', $text, $matches);
        return $matches[0];
    }
    
    // 获取中文词汇
    $chinese_words = chinese_segmentation($content);
    
    // 获取英文词汇
    $english_words = str_word_count(strip_tags($content), 1);
    
    // 合并所有词汇
    $all_words = array_merge($chinese_words, $english_words);
    
    // 过滤停用词
    $stop_words = array('的', '了', '在', '是', '和', '与', 'the', 'and', 'or', 'a', 'an');
    $filtered_words = array_diff($all_words, $stop_words);
    
    // 统计词频
    $word_freq = array_count_values($filtered_words);
    
    // 按频率排序
    arsort($word_freq);
    
    // 返回前N个关键词
    return array_slice($word_freq, 0, $limit, true);
}

/**
 * 清理过期缓存
 */
public function cleanup_expired_cache() {
    // WordPress对象缓存会自动处理过期
    // 这里可以添加自定义缓存清理逻辑
    $cleaned_count = 0;
    
    // 示例:清理过期的数据库缓存记录
    global $wpdb;
    $expired_time = date('Y-m-d H:i:s', time() - $this->cache_expiration);
    
    $cleaned_count = $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s AND option_value < %s",
            '_transient_ai_cache_%',
            $expired_time
        )
    );
    
    return $cleaned_count;
}

}

// 初始化缓存系统
$ai_cache = new AITaggingCache();

// 定期清理缓存
add_action('ai_tagging_daily_cleanup', array($ai_cache, 'cleanup_expired_cache'));
if (!wp_next_scheduled('ai_tagging_daily_cleanup')) {

wp_schedule_event(time(), 'daily', 'ai_tagging_daily_cleanup');

}


### 异步处理与队列系统

对于大量内容处理,异步处理可以显著提升用户体验:

/**

  • 异步标签处理系统
  • 使用WordPress后台任务处理大量内容
    */

class AsyncTaggingProcessor {

private $queue_name = 'ai_tagging_queue';

/**
 * 添加文章到处理队列
 */
public function add_to_queue($post_id, $priority = 'normal') {
    $queue_item = array(
        'post_id' => $post_id,
        'priority' => $priority,
        'added_at' => current_time('mysql'),
        'status' => 'pending'
    );
    
    // 保存到队列
    $queue = get_option($this->queue_name, array());
    $queue[] = $queue_item;
    update_option($this->queue_name, $queue);
    
    // 触发后台处理
    $this->schedule_background_processing();
    
    return true;
}

/**
 * 调度后台处理任务
 */
private function schedule_background_processing() {
    if (!wp_next_scheduled('process_ai_tagging_queue')) {
        wp_schedule_single_event(time() + 10, 'process_ai_tagging_queue');
    }
}

/**
 * 处理队列中的项目
 */
public function process_queue($batch_size = 10) {
    $queue = get_option($this->queue_name, array());
    
    if (empty($queue)) {
        return array('processed' => 0, 'remaining' => 0);
    }
    
    // 按优先级排序
    usort($queue, function($a, $b) {
        $priority_order = array('high' => 3, 'normal' => 2, 'low' => 1);
        return $priority_order[$b['priority']] - $priority_order[$a['priority']];
    });
    
    $processed = 0;
    $remaining = count($queue);
    
    foreach ($queue as $key => $item) {
        if ($processed >= $batch_size) {
            break;
        }
        
        if ($item['status'] === 'pending') {
            // 处理文章
            $this->process_single_post($item['post_id']);
            
            // 更新状态
            $queue[$key]['status'] = 'processed';
            $queue[$key]['processed_at'] = current_time('mysql');
            
            $processed++;
            $remaining--;
        }
    }
    
    // 清理已处理的项目
    $queue = array_filter($queue, function($item) {
        return $item['status'] === 'pending';
    });
    
    // 重新索引数组
    $queue = array_values($queue);
    
    update_option($this->queue_name, $queue);
    
    // 如果还有待处理项目,重新调度
    if (!empty($queue)) {
        $this->schedule_background_processing();
    }
    
    return array(
        'processed' => $processed,
        'remaining' => $remaining
    );
}

/**
 * 处理单篇文章
 */
private function process_single_post($post_id) {
    global $ai_cache;
    
    $post = get_post($post_id);
    if (!$post) {
        return false;
    }
    
    // 使用缓存系统进行分析
    $content = $post->post_title . ' ' . strip_tags($post->post_content);
    $analysis_result = $ai_cache->analyze_with_cache($content);
    
    // 生成并应用标签
    $tags = array();
    foreach ($analysis_result['entities'] as $entity) {
        if ($entity['confidence'] > 0.7) {
            $tags[] = $entity['name'];
        }
    }
    
    if (!empty($tags)) {
        $this->apply_tags_to_post($post_id, $tags);
    }
    
    // 记录处理日志
    $this->log_processing($post_id, count($tags));
    
    return true;
}

/**
 * 应用标签到文章
 */
private function apply_tags_to_post($post_id, $tags) {
    $tag_ids = array();
    
    foreach ($tags as $tag_name) {
        $term = term_exists($tag_name, 'post_tag');
        if (!$term) {
            $term = wp_insert_term($tag_name, 'post_tag');
        }
        
        if (!is_wp_error($term) && isset($term['term_id'])) {
            $tag_ids[] = (int)$term['term_id'];
        }
    }
    
    if (!empty($tag_ids)) {
        wp_set_post_terms($post_id, $tag_ids, 'post_tag', true);
    }
}

/**
 * 记录处理日志
 */
private function log_processing($post_id, $tag_count) {
    $log_entry = array(
        'post_id' => $post_id,
        'tag_count' => $tag_count,
        'processed_at' => current_time('mysql')
    );
    
    $logs = get_option('ai_tagging_logs', array());
    $logs[] = $log_entry;
    
    // 只保留最近1000条日志
    if (count($logs) > 1000) {
        $logs = array_slice($logs, -1000);
    }
    
    update_option('ai_tagging_logs', $logs);
}

/**
 * 获取队列状态
 */
public function get_queue_status() {
    $queue = get_option($this->queue_name, array());
    
    $pending = array_filter($queue, function($item) {
        return $item['status'] === 'pending';
    });
    
    $processed = array_filter($queue, function($item) {
        return $item['status'] === 'processed';
    });
    
    return array(
        'total' => count($queue),
        'pending' => count($pending),
        'processed' => count($processed)
    );
}

}

// 初始化异步处理器
$async_processor = new AsyncTaggingProcessor();

// 注册后台处理钩子
add_action('process_ai_tagging_queue', array($async_processor, 'process_queue'));

// 在文章保存时添加到队列
add_action('save_post', function($post_id) use ($async_processor) {

// 检查是否自动保存或修订
if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
    return;
}

// 检查文章类型
$post_type = get_post_type($post_id);
if ($post_type !== 'post') {
    return;
}

// 添加到处理队列
$async_processor->add_to_queue($post_id, 'high');

}, 20, 1);


## 监控与维护

### 性能监控系统

/**

  • 智能标签系统性能监控
    */

class AITaggingMonitor {

private $stats_option = 'ai_tagging_stats';

/**
 * 记录处理统计
 */
public function record_processing_stat($post_id, $processing_time, $tag_count, $success = true) {
    $stats = get_option($this->stats_option, array(
        'total_processed' => 0,
        'total_tags_generated' => 0,
        'total_processing_time' => 0,
        'avg_processing_time' => 0,
        'success_rate' => 0,
        'daily_stats' => array()
    ));
    
    // 更新总体统计
    $stats['total_processed']++;
    $stats['total_tags_generated'] += $tag_count;
    $stats['total_processing_time'] += $processing_time;
    $stats['avg_processing_time'] = $stats['total_processing_time'] / $stats['total_processed'];
    
    // 更新成功率
    $success_count = isset($stats['success_count']) ? $stats['success_count'] : 0;
    if ($success) {
        $success_count++;
    }
    $stats['success_count'] = $success_count;
    $stats['success_rate'] = ($success_count / $stats['total_processed']) * 100;
    
    // 更新每日统计
    $today = date('Y-m-d');
    if (!isset($stats['daily_stats'][$today])) {
        $stats['daily_stats'][$today] = array(
            'processed' => 0,
            'tags_generated' => 0,
            'avg_time' => 0
        );
    }
    
    $stats['daily_stats'][$today]['processed']++;
    $stats['daily_stats'][$today]['tags_generated'] += $tag_count;
    
    // 保存更新后的统计
    update_option($this->stats_option, $stats);
    
    // 记录详细日志
    $this->log_detailed_stat($post_id, $processing_time, $tag_count, $success);
}

/**
 * 记录详细统计日志
 */
private function log_detailed_stat($post_id, $processing_time, $tag_count, $success) {
    $log_entry = array(
        'timestamp' => current_time('mysql'),
        'post_id' => $post_id,
        'processing_time' => $processing_time,
        'tag_count' => $tag_count,
        'success' => $success
    );
    
    $logs = get_option('ai_tagging_detailed_logs', array());
    $logs[] = $log_entry;
    
    // 限制日志数量
    if (count($logs) > 10000) {
        $logs = array_slice($logs, -10000);
    }
    
    update_option('ai_tagging_detailed_logs', $logs, false);
}

/**
 * 获取性能报告
 */
public function get_performance_report($days = 7) {
    $stats = get_option($this->stats_option, array());
    $report = array(
        'overall' => array(),
        'daily' => array(),
        'recommendations' => array()
    );
    
    // 总体统计
    $report['overall'] = array(
        'total_processed' => $stats['total_processed'] ?? 0,
        'avg_processing_time' => round($stats['avg_processing_time'] ?? 0, 3),
        'success_rate' => round($stats['success_rate'] ?? 0, 2),
        'avg_tags_per_post' => $stats['total_processed'] > 0 
            ? round(($stats['total_tags_generated'] ?? 0) / $stats['total_processed'], 2) 
            : 0
    );
    
    // 每日统计
    $daily_stats = $stats['daily_stats'] ?? array();
    $dates = array_keys($daily_stats);
    rsort($dates);
    
    $recent_dates = array_slice($dates, 0, $days);
    foreach ($recent_dates as $date) {
        $report['daily'][$date] = $daily_stats[$date];
    }
    
    // 性能建议
    $avg_time = $report['overall']['avg_processing_time'];
    if ($avg_time > 5
本文来自网络投稿,不代表本站点的立场,转载请注明出处:https://www.gongxiangcang.com/6640.html

溯源库®作者

漳州柔性供应链服务有限公司 小批量订单定制化服务商( 投稿邮箱:vip@jiaochengku.com)
上一篇
下一篇

为您推荐

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@suyuanku.com

工作时间:周一至周五,9:00-17:30,节假日休息
关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部