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

WordPress网络传媒柔性内容智能标签插件应用教程

WordPress网络传媒柔性内容智能标签插件应用教程

一、插件概述与安装配置

1.1 什么是柔性内容智能标签插件

在当今内容爆炸的网络传媒时代,如何高效管理和组织海量内容成为每个WordPress站长的挑战。柔性内容智能标签插件正是为解决这一问题而设计的智能工具,它能够自动分析文章内容,提取关键词并智能分配标签,大大减轻人工标注的工作量。

1.2 插件安装步骤

首先,我们需要在WordPress后台安装并激活插件:

/**
 * 安装智能标签插件的几种方法
 * 方法一:通过WordPress后台直接搜索安装
 * 1. 登录WordPress后台
 * 2. 进入"插件" → "安装插件"
 * 3. 搜索"Flexible Content Smart Tags"
 * 4. 点击"立即安装"并激活
 * 
 * 方法二:通过FTP手动安装
 * 1. 下载插件ZIP文件
 * 2. 解压到wp-content/plugins/目录
 * 3. 在后台插件页面激活
 */

// 插件激活时的初始化设置
register_activation_hook(__FILE__, 'fcs_tags_activate');
function fcs_tags_activate() {
    // 创建必要的数据库表
    global $wpdb;
    $table_name = $wpdb->prefix . 'fcs_tag_logs';
    
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        post_id bigint(20) NOT NULL,
        tags_generated text NOT NULL,
        generation_time datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 设置默认选项
    add_option('fcs_tags_auto_generate', '1');
    add_option('fcs_tags_max_count', '5');
    add_option('fcs_tags_min_word_length', '3');
}

二、核心功能配置详解

2.1 基础设置与参数调整

安装完成后,进入"设置" → "智能标签"进行配置:

/**
 * 智能标签插件配置类
 * 包含所有可配置参数和默认值
 */
class FCS_Tags_Configuration {
    
    // 默认配置参数
    private $default_settings = array(
        'auto_generate'     => true,      // 是否自动生成标签
        'max_tags'          => 5,         // 每篇文章最大标签数
        'min_word_length'   => 3,         // 关键词最小长度
        'exclude_words'     => '的,和,在,了,是', // 排除词列表
        'use_existing_tags' => true,      // 是否优先使用现有标签
        'confidence_level'  => 0.7,       // 置信度阈值
        'update_frequency'  => 'publish', // 更新时机:publish/save/hourly
    );
    
    /**
     * 获取配置选项
     * @param string $key 配置键名
     * @return mixed 配置值
     */
    public function get_option($key) {
        $options = get_option('fcs_tags_settings', $this->default_settings);
        return isset($options[$key]) ? $options[$key] : $this->default_settings[$key];
    }
    
    /**
     * 保存配置
     * @param array $new_settings 新配置数组
     */
    public function save_settings($new_settings) {
        $sanitized_settings = array();
        
        // 清理和验证每个设置项
        $sanitized_settings['auto_generate'] = !empty($new_settings['auto_generate']);
        $sanitized_settings['max_tags'] = absint($new_settings['max_tags']);
        $sanitized_settings['min_word_length'] = max(2, absint($new_settings['min_word_length']));
        $sanitized_settings['confidence_level'] = min(1.0, max(0.1, floatval($new_settings['confidence_level'])));
        
        update_option('fcs_tags_settings', $sanitized_settings);
        
        // 记录配置更改
        $this->log_config_change($sanitized_settings);
    }
    
    /**
     * 记录配置更改日志
     */
    private function log_config_change($settings) {
        // 实现日志记录逻辑
        error_log('FCS Tags配置已更新: ' . json_encode($settings));
    }
}

2.2 智能标签生成算法

插件的核心是智能标签生成算法,它结合了多种自然语言处理技术:

/**
 * 智能标签生成器类
 * 负责分析内容并生成相关标签
 */
class FCS_Tag_Generator {
    
    /**
     * 从文章内容生成标签
     * @param string $content 文章内容
     * @param int $post_id 文章ID
     * @return array 生成的标签数组
     */
    public function generate_tags($content, $post_id = 0) {
        // 1. 文本预处理
        $processed_content = $this->preprocess_content($content);
        
        // 2. 分词处理
        $words = $this->segment_words($processed_content);
        
        // 3. 去除停用词
        $filtered_words = $this->remove_stopwords($words);
        
        // 4. 词频统计和权重计算
        $weighted_terms = $this->calculate_weights($filtered_words);
        
        // 5. 与现有标签库匹配
        $matched_tags = $this->match_existing_tags($weighted_terms);
        
        // 6. 新标签生成(如果需要)
        $new_tags = $this->generate_new_tags($weighted_terms, $matched_tags);
        
        // 7. 合并并排序结果
        $all_tags = array_merge($matched_tags, $new_tags);
        usort($all_tags, function($a, $b) {
            return $b['weight'] - $a['weight'];
        });
        
        // 8. 限制标签数量
        $max_tags = get_option('fcs_tags_max_count', 5);
        $final_tags = array_slice($all_tags, 0, $max_tags);
        
        // 9. 保存生成结果
        if ($post_id) {
            $this->save_generated_tags($post_id, $final_tags);
        }
        
        return $final_tags;
    }
    
    /**
     * 文本预处理:去除HTML标签,特殊字符等
     */
    private function preprocess_content($content) {
        // 移除HTML标签
        $content = wp_strip_all_tags($content);
        
        // 移除短代码
        $content = strip_shortcodes($content);
        
        // 转换为小写(中文不需要)
        if (!preg_match('/[x{4e00}-x{9fa5}]/u', $content)) {
            $content = strtolower($content);
        }
        
        // 移除特殊字符和数字
        $content = preg_replace('/[0-9]+/', '', $content);
        $content = preg_replace('/[^wsx{4e00}-x{9fa5}]/u', ' ', $content);
        
        return $content;
    }
    
    /**
     * 分词处理(支持中英文)
     */
    private function segment_words($text) {
        // 如果是中文内容,使用中文分词
        if (preg_match('/[x{4e00}-x{9fa5}]/u', $text)) {
            // 使用jieba分词(需要服务器支持)
            // 或者使用简单的按字符分割
            preg_match_all('/[x{4e00}-x{9fa5}]{2,}/u', $text, $matches);
            $chinese_words = $matches[0];
            
            // 提取英文单词
            preg_match_all('/[a-zA-Z]{3,}/', $text, $matches);
            $english_words = $matches[0];
            
            return array_merge($chinese_words, $english_words);
        } else {
            // 英文内容,按空格分割
            return preg_split('/s+/', $text);
        }
    }
}

三、高级功能与自定义开发

3.1 自定义标签规则

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

/**
 * 自定义标签规则示例
 * 为特定分类的文章添加特定标签
 */
add_filter('fcs_tags_before_save', 'custom_tag_rules', 10, 3);

function custom_tag_rules($tags, $post_id, $post_type) {
    $post_categories = wp_get_post_categories($post_id);
    
    // 示例:为科技类文章自动添加"科技创新"标签
    if (in_array(1, $post_categories)) { // 假设1是科技分类ID
        $tags[] = array(
            'name' => '科技创新',
            'weight' => 0.9,
            'source' => 'category_rule'
        );
    }
    
    // 示例:根据文章标题添加标签
    $post_title = get_the_title($post_id);
    if (strpos($post_title, '教程') !== false) {
        $tags[] = array(
            'name' => '教程指南',
            'weight' => 0.8,
            'source' => 'title_rule'
        );
    }
    
    // 去重并重新排序
    $unique_tags = array();
    foreach ($tags as $tag) {
        $unique_tags[$tag['name']] = $tag;
    }
    
    return array_values($unique_tags);
}

/**
 * 自定义停用词列表
 */
add_filter('fcs_tags_stopwords', 'custom_stopwords_list');

function custom_stopwords_list($default_stopwords) {
    // 添加自定义停用词
    $custom_stopwords = array(
        '我们', '你们', '他们', '这个', '那个',
        'some', 'very', 'just', 'like', 'with'
    );
    
    return array_merge($default_stopwords, $custom_stopwords);
}

3.2 批量处理现有内容

对于已有大量内容的网站,可以使用批量处理功能:

/**
 * 批量处理现有文章添加智能标签
 * 可以通过WP-CLI或后台批量工具执行
 */
class FCS_Batch_Processor {
    
    /**
     * 批量处理指定范围内的文章
     * @param int $limit 每次处理的数量
     * @param int $offset 偏移量
     * @return array 处理结果统计
     */
    public function batch_process_posts($limit = 50, $offset = 0) {
        $args = array(
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => $limit,
            'offset'         => $offset,
            'fields'         => 'ids'
        );
        
        $post_ids = get_posts($args);
        $results = array(
            'processed' => 0,
            'updated'   => 0,
            'failed'    => 0
        );
        
        foreach ($post_ids as $post_id) {
            try {
                $content = get_post_field('post_content', $post_id);
                $generator = new FCS_Tag_Generator();
                $tags = $generator->generate_tags($content, $post_id);
                
                if (!empty($tags)) {
                    $this->apply_tags_to_post($post_id, $tags);
                    $results['updated']++;
                }
                
                $results['processed']++;
                
                // 避免服务器压力,每次处理间隔0.1秒
                usleep(100000);
                
            } catch (Exception $e) {
                error_log("处理文章{$post_id}失败: " . $e->getMessage());
                $results['failed']++;
            }
        }
        
        return $results;
    }
    
    /**
     * 将标签应用到文章
     */
    private function apply_tags_to_post($post_id, $tags) {
        $tag_names = array();
        foreach ($tags as $tag) {
            $tag_names[] = $tag['name'];
        }
        
        wp_set_post_tags($post_id, $tag_names, true);
        
        // 记录处理日志
        update_post_meta($post_id, '_fcs_tags_auto_generated', current_time('mysql'));
        update_post_meta($post_id, '_fcs_tags_list', $tag_names);
    }
}

四、实际应用案例与优化建议

4.1 新闻门户网站应用案例

某大型新闻门户网站使用智能标签插件后,实现了以下改进:

  1. 自动化程度提升:编辑人员无需手动添加标签,节省70%的内容处理时间
  2. 标签一致性增强:避免不同编辑使用不同标签描述相同内容
  3. 相关内容推荐准确率提高:基于智能标签的相关文章推荐点击率提升45%

4.2 性能优化建议

/**
 * 智能标签插件性能优化方案
 */

// 1. 启用对象缓存
add_filter('fcs_tags_use_cache', '__return_true');

// 2. 设置合理的处理时间限制
add_filter('fcs_tags_time_limit', function() {
    return 30; // 最多执行30秒
});

// 3. 限制处理内容长度
add_filter('fcs_tags_max_content_length', function() {
    return 10000; // 最多处理10000字符
});

// 4. 异步处理长篇文章
add_action('save_post', 'async_tag_generation', 20, 3);

function async_tag_generation($post_id, $post, $update) {
    // 跳过自动保存和修订版
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if ($post->post_status == 'auto-draft') return;
    
    // 如果文章内容超过5000字符,使用异步处理
    if (strlen($post->post_content) > 5000) {
        wp_schedule_single_event(time() + 5, 'fcs_async_generate_tags', array($post_id));
    }
}

// 5. 定期清理旧日志
register_deactivation_hook(__FILE__, 'fcs_cleanup_scheduled_tasks');

function fcs_cleanup_scheduled_tasks() {
    $timestamp = wp_next_scheduled('fcs_daily_cleanup');
    wp_unschedule_event($timestamp, 'fcs_daily_cleanup');
}

// 设置每日清理任务
if (!wp_next_scheduled('fcs_daily_cleanup')) {
    wp_schedule_event(time(), 'daily', 'fcs_daily_cleanup');
}

add_action('fcs_daily_cleanup', 'fcs_cleanup_old_logs');

function fcs_cleanup_old_logs() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'fcs_tag_logs';
    $thirty_days_ago = date('Y-m-d H:i:s', strtotime('-30 days'));
    
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM $table_name WHERE generation_time < %s",
            $thirty_days_ago
        )
    );
}

4.3 监控与维护

建议定期监控插件的运行状态:

  1. 查看生成日志:了解标签生成的成功率和质量
  2. 分析标签使用情况:定期检查最常用的标签,优化标签库
  3. 用户反馈收集:让编辑人员报告标签不准确的情况,用于改进算法
  4. 性能监控:确保插件不会影响网站加载速度

五、总结

WordPress柔性内容智能标签插件为网络传媒网站提供了强大的内容管理工具。通过本文的教程,您应该能够:

  1. 正确安装和配置插件
  2. 理解智能标签生成的基本原理
  3. 根据自身需求进行自定义开发
  4. 实施性能优化策略
  5. 建立有效的监控和维护流程

随着人工智能技术的不断发展,智能内容管理将成为网络传媒行业的标配工具。合理利用这类插件,不仅能提高工作效率,还能通过更精准的内容组织提升用户体验和网站粘性。

记住,任何自动化工具都需要人工监督和定期优化。建议每季度审查一次标签生成规则和结果,确保插件始终符合您网站内容战略的发展方向。

六、API接口与第三方集成

6.1 插件REST API开发

智能标签插件提供完整的REST API接口,方便与其他系统集成:

/**
 * 智能标签插件REST API接口
 * 提供外部系统调用能力
 */
class FCS_Tags_REST_API {
    
    public function __construct() {
        add_action('rest_api_init', array($this, 'register_routes'));
    }
    
    /**
     * 注册REST API路由
     */
    public function register_routes() {
        // 获取文章标签接口
        register_rest_route('fcs-tags/v1', '/post/(?P<id>d+)/tags', array(
            'methods'  => WP_REST_Server::READABLE,
            'callback' => array($this, 'get_post_tags'),
            'args'     => array(
                'id' => array(
                    'validate_callback' => function($param) {
                        return is_numeric($param) && get_post($param);
                    }
                ),
            ),
            'permission_callback' => array($this, 'check_api_permission')
        ));
        
        // 生成标签接口
        register_rest_route('fcs-tags/v1', '/generate', array(
            'methods'  => WP_REST_Server::CREATABLE,
            'callback' => array($this, 'generate_tags_api'),
            'args'     => array(
                'content' => array(
                    'required' => true,
                    'validate_callback' => 'is_string'
                ),
                'title' => array(
                    'required' => false,
                    'validate_callback' => 'is_string'
                ),
            ),
            'permission_callback' => array($this, 'check_api_permission')
        ));
        
        // 批量处理接口
        register_rest_route('fcs-tags/v1', '/batch-process', array(
            'methods'  => WP_REST_Server::CREATABLE,
            'callback' => array($this, 'batch_process_api'),
            'args'     => array(
                'post_ids' => array(
                    'required' => true,
                    'validate_callback' => function($param) {
                        if (!is_array($param)) return false;
                        foreach ($param as $id) {
                            if (!is_numeric($id) || !get_post($id)) {
                                return false;
                            }
                        }
                        return true;
                    }
                ),
            ),
            'permission_callback' => array($this, 'check_api_permission')
        ));
    }
    
    /**
     * 获取文章标签API
     */
    public function get_post_tags($request) {
        $post_id = $request['id'];
        $force_regenerate = isset($request['regenerate']) ? $request['regenerate'] : false;
        
        // 如果强制重新生成或没有标签
        if ($force_regenerate || !wp_get_post_tags($post_id)) {
            $content = get_post_field('post_content', $post_id);
            $generator = new FCS_Tag_Generator();
            $tags = $generator->generate_tags($content, $post_id);
        } else {
            $tags = wp_get_post_tags($post_id);
        }
        
        // 格式化响应数据
        $formatted_tags = array();
        foreach ($tags as $tag) {
            $formatted_tags[] = array(
                'id'   => $tag->term_id,
                'name' => $tag->name,
                'slug' => $tag->slug,
                'url'  => get_tag_link($tag->term_id)
            );
        }
        
        return rest_ensure_response(array(
            'success' => true,
            'post_id' => $post_id,
            'tags'    => $formatted_tags,
            'count'   => count($formatted_tags)
        ));
    }
    
    /**
     * 生成标签API
     */
    public function generate_tags_api($request) {
        $content = $request['content'];
        $title = $request['title'] ?? '';
        
        // 结合标题和内容进行分析
        $full_content = $title . ' ' . $content;
        
        $generator = new FCS_Tag_Generator();
        $tags = $generator->generate_tags($full_content);
        
        // 提取标签名称
        $tag_names = array_column($tags, 'name');
        
        return rest_ensure_response(array(
            'success' => true,
            'tags'    => $tag_names,
            'details' => $tags,
            'count'   => count($tags)
        ));
    }
    
    /**
     * API权限检查
     */
    public function check_api_permission($request) {
        // 可以根据需要设置不同的权限策略
        // 示例:检查API密钥或用户权限
        
        // 方法1:使用API密钥
        $api_key = $request->get_header('X-API-Key');
        if ($api_key && $this->validate_api_key($api_key)) {
            return true;
        }
        
        // 方法2:检查用户权限
        if (current_user_can('edit_posts')) {
            return true;
        }
        
        return new WP_Error(
            'rest_forbidden',
            __('抱歉,您没有权限访问此API。'),
            array('status' => 403)
        );
    }
    
    /**
     * 验证API密钥
     */
    private function validate_api_key($api_key) {
        $valid_keys = get_option('fcs_api_keys', array());
        return in_array(hash('sha256', $api_key), $valid_keys);
    }
}

// 初始化REST API
new FCS_Tags_REST_API();

6.2 与第三方AI服务集成

/**
 * 第三方AI服务集成类
 * 支持OpenAI、百度AI等第三方服务
 */
class FCS_AI_Service_Integration {
    
    private $service_type;
    private $api_key;
    
    public function __construct($service_type = 'openai') {
        $this->service_type = $service_type;
        $this->api_key = $this->get_api_key($service_type);
    }
    
    /**
     * 使用AI服务生成标签
     */
    public function generate_tags_with_ai($content, $options = array()) {
        switch ($this->service_type) {
            case 'openai':
                return $this->call_openai_api($content, $options);
            case 'baidu':
                return $this->call_baidu_api($content, $options);
            case 'tencent':
                return $this->call_tencent_api($content, $options);
            default:
                return $this->call_openai_api($content, $options);
        }
    }
    
    /**
     * 调用OpenAI API
     */
    private function call_openai_api($content, $options) {
        $max_tokens = $options['max_tokens'] ?? 100;
        $temperature = $options['temperature'] ?? 0.7;
        
        // 构建提示词
        $prompt = $this->build_openai_prompt($content);
        
        $response = wp_remote_post('https://api.openai.com/v1/completions', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type'  => 'application/json',
            ),
            'body' => json_encode(array(
                'model'       => 'text-davinci-003',
                'prompt'      => $prompt,
                'max_tokens'  => $max_tokens,
                'temperature' => $temperature,
                'n'           => 1,
            )),
            'timeout' => 30,
        ));
        
        if (is_wp_error($response)) {
            error_log('OpenAI API调用失败: ' . $response->get_error_message());
            return false;
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['choices'][0]['text'])) {
            return $this->parse_ai_response($body['choices'][0]['text']);
        }
        
        return false;
    }
    
    /**
     * 构建OpenAI提示词
     */
    private function build_openai_prompt($content) {
        $content_preview = wp_trim_words($content, 200);
        
        return "请分析以下文章内容,生成5个最相关的标签。要求:
        1. 标签用逗号分隔
        2. 只返回标签,不要其他文字
        3. 标签要简洁明了
        
        文章内容:
        {$content_preview}
        
        标签:";
    }
    
    /**
     * 解析AI响应
     */
    private function parse_ai_response($response) {
        // 清理响应文本
        $response = trim($response);
        $response = str_replace(array('标签:', 'Tags:', '标签:', ' '), '', $response);
        
        // 分割标签
        $tags = explode(',', $response);
        
        // 清理每个标签
        $cleaned_tags = array();
        foreach ($tags as $tag) {
            $tag = trim($tag);
            if (!empty($tag) && strlen($tag) >= 2) {
                $cleaned_tags[] = $tag;
            }
        }
        
        return array_slice($cleaned_tags, 0, 5);
    }
    
    /**
     * 获取API密钥
     */
    private function get_api_key($service_type) {
        $option_name = 'fcs_ai_' . $service_type . '_api_key';
        return get_option($option_name, '');
    }
}

/**
 * 使用AI服务生成标签的过滤器
 */
add_filter('fcs_tags_generated', 'enhance_tags_with_ai', 10, 3);

function enhance_tags_with_ai($tags, $content, $post_id) {
    $use_ai = get_option('fcs_use_ai_enhancement', false);
    
    if (!$use_ai || empty($content)) {
        return $tags;
    }
    
    // 如果本地生成的标签太少,使用AI补充
    if (count($tags) < 3) {
        $ai_service = new FCS_AI_Service_Integration('openai');
        $ai_tags = $ai_service->generate_tags_with_ai($content);
        
        if ($ai_tags) {
            // 合并标签,避免重复
            $existing_tag_names = array_column($tags, 'name');
            foreach ($ai_tags as $ai_tag) {
                if (!in_array($ai_tag, $existing_tag_names)) {
                    $tags[] = array(
                        'name'   => $ai_tag,
                        'weight' => 0.6, // AI生成的标签权重稍低
                        'source' => 'ai_service'
                    );
                }
            }
        }
    }
    
    return $tags;
}

七、前端展示与用户体验

7.1 智能标签云展示

/**
 * 智能标签云小工具
 * 根据标签使用频率和相关性动态展示
 */
class FCS_Smart_Tag_Cloud_Widget extends WP_Widget {
    
    public function __construct() {
        parent::__construct(
            'fcs_smart_tag_cloud',
            __('智能标签云', 'fcs-tags'),
            array('description' => __('基于内容相关性的智能标签云', 'fcs-tags'))
        );
    }
    
    /**
     * 前端展示
     */
    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'];
        }
        
        // 获取智能标签云
        $tag_cloud = $this->generate_smart_tag_cloud($instance);
        echo $tag_cloud;
        
        echo $args['after_widget'];
    }
    
    /**
     * 生成智能标签云
     */
    private function generate_smart_tag_cloud($instance) {
        $max_tags = $instance['max_tags'] ?? 45;
        $min_size = $instance['min_font_size'] ?? 12;
        $max_size = $instance['max_font_size'] ?? 32;
        $current_post_id = get_the_ID();
        
        // 获取相关标签
        $tags = $this->get_contextual_tags($current_post_id, $max_tags);
        
        if (empty($tags)) {
            return '<p class="no-tags">' . __('暂无标签', 'fcs-tags') . '</p>';
        }
        
        // 计算标签大小
        $tag_sizes = $this->calculate_tag_sizes($tags, $min_size, $max_size);
        
        // 生成HTML
        $output = '<div class="fcs-smart-tag-cloud">';
        foreach ($tags as $tag) {
            $font_size = $tag_sizes[$tag->term_id];
            $color = $this->generate_tag_color($tag->term_id);
            
            $output .= sprintf(
                '<a href="%s" class="tag-link tag-%d" style="font-size: %dpx; color: %s;" title="%s">%s</a> ',
                esc_url(get_tag_link($tag->term_id)),
                $tag->term_id,
                $font_size,
                $color,
                sprintf(__('查看%s相关文章', 'fcs-tags'), $tag->name),
                esc_html($tag->name)
            );
        }
        $output .= '</div>';
        
        // 添加相关文章推荐
        if ($instance['show_related'] ?? false) {
            $output .= $this->get_related_posts_section($current_post_id);
        }
        
        return $output;
    }
    
    /**
     * 获取上下文相关标签
     */
    private function get_contextual_tags($post_id, $max_tags) {
        // 如果是单篇文章页面,优先显示相关标签
        if ($post_id && is_single()) {
            $post_tags = wp_get_post_tags($post_id);
            
            if (!empty($post_tags)) {
                // 获取相关标签(同分类下的热门标签)
                $related_tags = $this->get_related_tags($post_tags, $max_tags);
                return $related_tags;
            }
        }
        
        // 默认显示全站热门标签
        return get_tags(array(
            'orderby' => 'count',
            'order'   => 'DESC',
            'number'  => $max_tags,
            'hide_empty' => true
        ));
    }
    
    /**
     * 获取相关标签
     */
    private function get_related_tags($post_tags, $max_tags) {
        $tag_ids = wp_list_pluck($post_tags, 'term_id');
        
        // 获取使用相同标签的文章
        $related_args = array(
            'tag__in'        => $tag_ids,
            'post__not_in'   => array(get_the_ID()),
            'posts_per_page' => 20,
            'fields'         => 'ids'
        );
        
        $related_posts = get_posts($related_args);
        
        if (empty($related_posts)) {
            return $post_tags;
        }
        
        // 获取这些文章的所有标签
        $all_tags = wp_get_object_terms($related_posts, 'post_tag');
        
        // 统计标签出现次数
        $tag_counts = array();
        foreach ($all_tags as $tag) {
            if (!in_array($tag->term_id, $tag_ids)) {
                if (!isset($tag_counts[$tag->term_id])) {
                    $tag_counts[$tag->term_id] = 0;
                }
                $tag_counts[$tag->term_id]++;
            }
        }
        
        // 按出现次数排序
        arsort($tag_counts);
        
        // 获取标签对象
        $related_tag_ids = array_slice(array_keys($tag_counts), 0, $max_tags - count($tag_ids));
        $related_tags = get_tags(array(
            'include' => $related_tag_ids,
            'orderby' => 'include'
        ));
        
        // 合并原始标签和相关标签
        return array_merge($post_tags, $related_tags);
    }
    
    /**
     * 小工具后台表单
     */
    public function form($instance) {
        $title = $instance['title'] ?? __('智能标签', 'fcs-tags');
        $max_tags = $instance['max_tags'] ?? 45;
        $min_size = $instance['min_font_size'] ?? 12;
        $max_size = $instance['max_font_size'] ?? 32;
        $show_related = $instance['show_related'] ?? false;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>">
                <?php _e('标题:', 'fcs-tags'); ?>
            </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('max_tags'); ?>">
                <?php _e('最多显示标签数:', 'fcs-tags'); ?>
            </label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('max_tags'); ?>"
                   name="<?php echo $this->get_field_name('max_tags'); ?>"
                   type="number" min="10" max="100" value="<?php echo esc_attr($max_tags); ?>">
        </p>
        
        <p>
            <label for="<?php echo $this->get_field_id('min_font_size'); ?>">
                <?php _e('最小字体大小(px):', 'fcs-tags'); ?>
            </label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('min_font_size'); ?>"
                   name="<?php echo $this->get_field_name('min_font_size'); ?>"
                   type="number" min="8" max="20" value="<?php echo esc_attr($min_size); ?>">
        </p>
        
        <p>
            <label for="<?php echo $this->get_field_id('max_font_size'); ?>">
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5899.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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