首页 / 教程文章 / 网络传媒WordPress站点柔性内容智能摘要插件开发教程

网络传媒WordPress站点柔性内容智能摘要插件开发教程

网络传媒WordPress站点柔性内容智能摘要插件开发教程

一、项目概述与需求分析

在当今信息爆炸的时代,网络传媒站点面临着内容过载的挑战。用户往往没有时间阅读完整的长篇文章,而一个精准的内容摘要可以显著提升用户体验和内容传播效率。本教程将指导您开发一款适用于WordPress的柔性内容智能摘要插件,该插件能够根据文章内容自动生成可自定义长度的智能摘要。

核心功能需求:

  1. 自动分析文章内容并提取关键信息
  2. 支持自定义摘要长度和输出格式
  3. 智能识别文章类型和结构
  4. 提供手动调整摘要的选项
  5. 兼容主流WordPress主题和插件

二、开发环境搭建与插件基础结构

首先,我们需要创建一个标准的WordPress插件目录结构:

flexible-smart-excerpt/
├── flexible-smart-excerpt.php      # 主插件文件
├── includes/
│   ├── class-excerpt-generator.php # 摘要生成核心类
│   ├── class-settings.php          # 设置页面类
│   └── class-frontend.php          # 前端显示类
├── assets/
│   ├── css/
│   │   └── admin-style.css         # 后台样式
│   └── js/
│       └── admin-script.js         # 后台脚本
└── languages/                      # 国际化文件目录

主插件文件基础代码

<?php
/**
 * Plugin Name: 柔性内容智能摘要
 * Plugin URI:  https://yourwebsite.com/flexible-smart-excerpt
 * Description: 为网络传媒WordPress站点提供智能内容摘要生成功能
 * Version:     1.0.0
 * Author:      您的名称
 * License:     GPL v2 or later
 * Text Domain: flexible-smart-excerpt
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('FSE_VERSION', '1.0.0');
define('FSE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FSE_PLUGIN_URL', plugin_dir_url(__FILE__));

// 自动加载类文件
spl_autoload_register(function ($class_name) {
    if (strpos($class_name, 'FSE_') === 0) {
        $file = FSE_PLUGIN_DIR . 'includes/class-' . strtolower(str_replace('_', '-', substr($class_name, 4))) . '.php';
        if (file_exists($file)) {
            require_once $file;
        }
    }
});

// 初始化插件
add_action('plugins_loaded', 'fse_init_plugin');

function fse_init_plugin() {
    // 加载文本域用于国际化
    load_plugin_textdomain('flexible-smart-excerpt', false, dirname(plugin_basename(__FILE__)) . '/languages/');
    
    // 初始化核心类
    if (is_admin()) {
        new FSE_Settings();
    }
    
    new FSE_Excerpt_Generator();
    new FSE_Frontend();
}

三、智能摘要生成核心算法

摘要生成器类实现

<?php
/**
 * 智能摘要生成核心类
 * 使用多种算法提取文章关键内容
 */
class FSE_Excerpt_Generator {
    
    private $options;
    
    public function __construct() {
        $this->options = get_option('fse_settings', array());
        
        // 挂钩到WordPress的摘要生成
        add_filter('the_excerpt', array($this, 'generate_smart_excerpt'), 10, 2);
        add_filter('get_the_excerpt', array($this, 'generate_smart_excerpt'), 10, 2);
    }
    
    /**
     * 生成智能摘要
     * @param string $excerpt 原始摘要
     * @param WP_Post $post 文章对象
     * @return string 处理后的摘要
     */
    public function generate_smart_excerpt($excerpt, $post = null) {
        // 如果已经有摘要且不是自动生成的,直接返回
        if (!empty($excerpt) && !$this->is_auto_generated_excerpt($excerpt, $post)) {
            return $excerpt;
        }
        
        // 获取文章内容
        $content = $this->get_post_content($post);
        
        // 根据设置选择摘要生成方法
        $method = isset($this->options['extraction_method']) ? 
                 $this->options['extraction_method'] : 'hybrid';
        
        switch ($method) {
            case 'lead_paragraph':
                $excerpt = $this->extract_lead_paragraph($content);
                break;
            case 'tfidf':
                $excerpt = $this->extract_by_tfidf($content);
                break;
            case 'hybrid':
            default:
                $excerpt = $this->hybrid_extraction($content);
                break;
        }
        
        // 清理和格式化摘要
        $excerpt = $this->clean_and_format_excerpt($excerpt);
        
        return $excerpt;
    }
    
    /**
     * 混合提取算法 - 结合多种方法获得最佳结果
     * @param string $content 文章内容
     * @return string 生成的摘要
     */
    private function hybrid_extraction($content) {
        // 移除HTML标签,保留段落结构
        $clean_content = strip_tags($content, '<p><br><h1><h2><h3><h4>');
        
        // 方法1:提取前导段落
        $lead_excerpt = $this->extract_lead_paragraph($clean_content);
        
        // 方法2:基于TF-IDF的关键句提取
        $tfidf_excerpt = $this->extract_by_tfidf($clean_content);
        
        // 方法3:提取包含关键词的句子
        $keyword_excerpt = $this->extract_by_keywords($clean_content);
        
        // 根据算法评分选择最佳摘要
        $scores = array(
            'lead' => $this->score_excerpt($lead_excerpt),
            'tfidf' => $this->score_excerpt($tfidf_excerpt),
            'keyword' => $this->score_excerpt($keyword_excerpt)
        );
        
        // 选择评分最高的摘要
        arsort($scores);
        $best_method = key($scores);
        
        switch ($best_method) {
            case 'lead':
                return $lead_excerpt;
            case 'tfidf':
                return $tfidf_excerpt;
            case 'keyword':
                return $keyword_excerpt;
            default:
                return $lead_excerpt;
        }
    }
    
    /**
     * 基于TF-IDF算法的关键句提取
     * @param string $content 文章内容
     * @return string 提取的摘要
     */
    private function extract_by_tfidf($content) {
        // 将内容分割成句子
        $sentences = $this->split_into_sentences($content);
        
        if (empty($sentences)) {
            return '';
        }
        
        // 计算每个词的TF-IDF值(简化版)
        $word_scores = $this->calculate_word_scores($sentences);
        
        // 计算每个句子的得分
        $sentence_scores = array();
        foreach ($sentences as $index => $sentence) {
            $score = 0;
            $words = $this->split_into_words($sentence);
            $word_count = count($words);
            
            if ($word_count > 0) {
                foreach ($words as $word) {
                    if (isset($word_scores[$word])) {
                        $score += $word_scores[$word];
                    }
                }
                $sentence_scores[$index] = $score / sqrt($word_count);
            }
        }
        
        // 选择得分最高的句子
        arsort($sentence_scores);
        $selected_indices = array_slice(array_keys($sentence_scores), 0, 3, true);
        sort($selected_indices);
        
        // 组合成摘要
        $excerpt_sentences = array();
        foreach ($selected_indices as $index) {
            $excerpt_sentences[] = $sentences[$index];
        }
        
        return implode(' ', $excerpt_sentences);
    }
    
    /**
     * 将文本分割成句子
     * @param string $text 输入文本
     * @return array 句子数组
     */
    private function split_into_sentences($text) {
        // 简单的句子分割,实际应用中可能需要更复杂的逻辑
        $sentences = preg_split('/(?<=[.!?])s+/', $text, -1, PREG_SPLIT_NO_EMPTY);
        return array_filter($sentences, function($sentence) {
            return strlen(trim($sentence)) > 10; // 过滤过短的句子
        });
    }
    
    /**
     * 清理和格式化摘要
     * @param string $excerpt 原始摘要
     * @return string 格式化后的摘要
     */
    private function clean_and_format_excerpt($excerpt) {
        // 获取摘要长度设置
        $length = isset($this->options['excerpt_length']) ? 
                 intval($this->options['excerpt_length']) : 150;
        
        // 截断到指定长度
        if (strlen($excerpt) > $length) {
            $excerpt = mb_substr($excerpt, 0, $length, 'UTF-8');
            
            // 确保不在单词中间截断
            $last_space = strrpos($excerpt, ' ');
            if ($last_space !== false) {
                $excerpt = substr($excerpt, 0, $last_space);
            }
            
            // 添加省略号
            $excerpt .= '...';
        }
        
        // 移除多余的空白字符
        $excerpt = preg_replace('/s+/', ' ', $excerpt);
        
        return trim($excerpt);
    }
    
    // 其他辅助方法...
}

四、插件设置页面开发

设置页面类实现

<?php
/**
 * 插件设置页面类
 */
class FSE_Settings {
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'settings_init'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    }
    
    /**
     * 添加管理菜单
     */
    public function add_admin_menu() {
        add_options_page(
            '柔性智能摘要设置',
            '智能摘要',
            'manage_options',
            'flexible-smart-excerpt',
            array($this, 'settings_page')
        );
    }
    
    /**
     * 初始化设置
     */
    public function settings_init() {
        register_setting('fse_settings_group', 'fse_settings');
        
        // 基本设置部分
        add_settings_section(
            'fse_basic_section',
            '基本设置',
            array($this, 'basic_section_callback'),
            'flexible-smart-excerpt'
        );
        
        // 摘要长度设置
        add_settings_field(
            'excerpt_length',
            '摘要长度',
            array($this, 'excerpt_length_render'),
            'flexible-smart-excerpt',
            'fse_basic_section'
        );
        
        // 提取方法设置
        add_settings_field(
            'extraction_method',
            '提取算法',
            array($this, 'extraction_method_render'),
            'flexible-smart-excerpt',
            'fse_basic_section'
        );
        
        // 高级设置部分
        add_settings_section(
            'fse_advanced_section',
            '高级设置',
            array($this, 'advanced_section_callback'),
            'flexible-smart-excerpt'
        );
        
        // 自定义关键词
        add_settings_field(
            'custom_keywords',
            '自定义关键词',
            array($this, 'custom_keywords_render'),
            'flexible-smart-excerpt',
            'fse_advanced_section'
        );
    }
    
    /**
     * 渲染摘要长度设置字段
     */
    public function excerpt_length_render() {
        $options = get_option('fse_settings');
        $value = isset($options['excerpt_length']) ? $options['excerpt_length'] : 150;
        ?>
        <input type="number" 
               name="fse_settings[excerpt_length]" 
               value="<?php echo esc_attr($value); ?>"
               min="50" 
               max="500" 
               step="10">
        <p class="description">摘要的字符长度(建议150-200字符)</p>
        <?php
    }
    
    /**
     * 渲染提取方法设置字段
     */
    public function extraction_method_render() {
        $options = get_option('fse_settings');
        $value = isset($options['extraction_method']) ? $options['extraction_method'] : 'hybrid';
        ?>
        <select name="fse_settings[extraction_method]">
            <option value="lead_paragraph" <?php selected($value, 'lead_paragraph'); ?>>
                前导段落法
            </option>
            <option value="tfidf" <?php selected($value, 'tfidf'); ?>>
                TF-IDF算法
            </option>
            <option value="hybrid" <?php selected($value, 'hybrid'); ?>>
                混合智能算法(推荐)
            </option>
        </select>
        <p class="description">选择摘要生成算法,混合算法综合效果最佳</p>
        <?php
    }
    
    /**
     * 设置页面HTML
     */
    public function settings_page() {
        ?>
        <div class="wrap">
            <h1>柔性内容智能摘要设置</h1>
            
            <div class="fse-settings-container">
                <div class="fse-main-settings">
                    <form action="options.php" method="post">
                        <?php
                        settings_fields('fse_settings_group');
                        do_settings_sections('flexible-smart-excerpt');
                        submit_button();
                        ?>
                    </form>
                </div>
                
                <div class="fse-sidebar">
                    <div class="fse-info-box">
                        <h3>使用说明</h3>
                        <p>1. 选择适合您站点的摘要长度</p>
                        <p>2. 根据内容类型选择合适的提取算法</p>
                        <p>3. 可在文章编辑页面手动调整自动生成的摘要</p>
                    </div>
                    
                    <div class="fse-info-box">
                        <h3>算法说明</h3>
                        <p><strong>前导段落法:</strong>提取文章开头段落,适合新闻类内容</p>
                        <p><strong>TF-IDF算法:</strong>基于词频统计,适合技术类文章</p>
                        <p><strong>混合算法:</strong>智能结合多种方法,适合综合性内容</p>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * 加载管理端资源
     */
    public function enqueue_admin_assets($hook) {
        if ($hook != 'settings_page_flexible-smart-excerpt') {
            return;
        }
        
        wp_enqueue_style(
            'fse-admin-style',
            FSE_PLUGIN_URL . 'assets/css/admin-style.css',
            array(),
            FSE_VERSION
        );
        
        wp_enqueue_script(
            'fse-admin-script',
            FSE_PLUGIN_URL . 'assets/js/admin-script.js',
            array('jquery'),
            FSE_VERSION,
            true
        );
    }
}

五、前端集成与显示优化

前端显示类实现

<?php
/**
 * 前端显示类
 * 处理摘要在前端的显示和样式
 */
class FSE_Frontend {
    
    public function __construct() {
        // 添加短代码支持
        add_shortcode('smart_excerpt', array($this, 'shortcode_handler'));
        
        // 添加文章列表摘要过滤器
        add_filter('the_excerpt', array($this, 'enhance_excerpt_display'), 20);
        
        // 添加CSS样式
        add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets'));
    }
    
    /**
     * 短码处理器
     * @param array $atts 短码属性
     * @return string 生成的摘要
     */
    public function shortcode_handler($atts) {
        $atts = shortcode_atts(array(
            'length' => 150,
            'post_id' => get_the_ID(),
            'read_more' => true
        ), $atts, 'smart_excerpt');
        
        $post_id = intval($atts['post_id']);
        $post = get_post($post_id);
        
        if (!$post) {
            return '';
        }
        
        // 生成摘要
        $excerpt = apply_filters('the_excerpt', $post->post_excerpt, $post);
        
        // 添加"阅读更多"链接
        if ($atts['read_more'] && !empty($excerpt)) {
            $excerpt .= sprintf(
                ' <a href="%s" class="fse-read-more">阅读全文</a>',
                esc_url(get_permalink($post_id))
            );
        }
        
        return '<div class="fse-excerpt">' . $excerpt . '</div>';
    }
    
    /**
     * 增强摘要显示
     */
    public function enhance_excerpt_display($excerpt) {
        if (is_admin() || empty($excerpt)) {
            return $excerpt;
        }
        
        // 添加摘要容器和样式类
        $excerpt = '<div class="fse-excerpt-content">' . $excerpt . '</div>';
        
        return $excerpt;
    }
    
    /**
     * 加载前端资源
     */
    public function enqueue_frontend_assets() {
        if (!is_singular() && !is_archive()) {
            return;
        }
        
        wp_enqueue_style(
            'fse-frontend-style',
            FSE_PLUGIN_URL . 'assets/css/frontend-style.css',
            array(),

六、插件功能扩展与优化

文章编辑页面集成

为了让编辑能够手动调整自动生成的摘要,我们需要在文章编辑页面添加摘要优化功能:

<?php
/**
 * 文章编辑页面摘要优化功能
 */
class FSE_Post_Editor {
    
    public function __construct() {
        add_action('add_meta_boxes', array($this, 'add_excerpt_meta_box'));
        add_action('save_post', array($this, 'save_excerpt_meta'), 10, 2);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_editor_assets'));
    }
    
    /**
     * 添加摘要优化元框
     */
    public function add_excerpt_meta_box() {
        $post_types = isset($this->options['post_types']) ? 
                     $this->options['post_types'] : array('post');
        
        foreach ($post_types as $post_type) {
            add_meta_box(
                'fse_excerpt_optimizer',
                '智能摘要优化',
                array($this, 'render_excerpt_meta_box'),
                $post_type,
                'side',
                'high'
            );
        }
    }
    
    /**
     * 渲染摘要优化元框
     */
    public function render_excerpt_meta_box($post) {
        wp_nonce_field('fse_excerpt_nonce', 'fse_excerpt_nonce_field');
        
        $current_excerpt = get_post_meta($post->ID, '_fse_optimized_excerpt', true);
        $auto_excerpt = $this->generate_auto_excerpt($post);
        
        ?>
        <div class="fse-excerpt-editor">
            <p><strong>自动生成摘要:</strong></p>
            <textarea id="fse_auto_excerpt" 
                      readonly 
                      class="widefat" 
                      rows="3"><?php echo esc_textarea($auto_excerpt); ?></textarea>
            
            <p><strong>自定义摘要:</strong></p>
            <textarea name="fse_custom_excerpt" 
                      id="fse_custom_excerpt" 
                      class="widefat" 
                      rows="3"
                      placeholder="如需覆盖自动摘要,请在此输入..."><?php echo esc_textarea($current_excerpt); ?></textarea>
            
            <div class="fse-excerpt-actions">
                <button type="button" 
                        id="fse_use_auto" 
                        class="button button-secondary">
                    使用自动摘要
                </button>
                <button type="button" 
                        id="fse_preview_excerpt" 
                        class="button button-secondary">
                    预览效果
                </button>
            </div>
            
            <div class="fse-excerpt-stats">
                <p>当前字数:<span id="fse_word_count">0</span> 字</p>
                <p>推荐长度:150-200字</p>
            </div>
        </div>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // 字数统计
            function updateWordCount() {
                var text = $('#fse_custom_excerpt').val();
                var wordCount = text.trim().length;
                $('#fse_word_count').text(wordCount);
            }
            
            // 使用自动摘要
            $('#fse_use_auto').click(function() {
                $('#fse_custom_excerpt').val($('#fse_auto_excerpt').val());
                updateWordCount();
            });
            
            // 初始化字数统计
            updateWordCount();
            $('#fse_custom_excerpt').on('input', updateWordCount);
        });
        </script>
        <?php
    }
    
    /**
     * 保存摘要元数据
     */
    public function save_excerpt_meta($post_id, $post) {
        // 安全检查
        if (!isset($_POST['fse_excerpt_nonce_field']) || 
            !wp_verify_nonce($_POST['fse_excerpt_nonce_field'], 'fse_excerpt_nonce')) {
            return;
        }
        
        // 权限检查
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 保存自定义摘要
        if (isset($_POST['fse_custom_excerpt'])) {
            $custom_excerpt = sanitize_textarea_field($_POST['fse_custom_excerpt']);
            update_post_meta($post_id, '_fse_optimized_excerpt', $custom_excerpt);
            
            // 如果自定义摘要不为空,更新文章摘要
            if (!empty($custom_excerpt)) {
                wp_update_post(array(
                    'ID' => $post_id,
                    'post_excerpt' => $custom_excerpt
                ));
            }
        }
    }
    
    /**
     * 生成自动摘要
     */
    private function generate_auto_excerpt($post) {
        $generator = new FSE_Excerpt_Generator();
        return $generator->generate_smart_excerpt('', $post);
    }
}

七、性能优化与缓存机制

实现摘要缓存系统

为了提高插件性能,我们需要实现缓存机制:

<?php
/**
 * 摘要缓存管理类
 */
class FSE_Cache_Manager {
    
    private $cache_group = 'fse_excerpts';
    private $cache_expiration = 86400; // 24小时
    
    public function __construct() {
        // 文章更新时清除缓存
        add_action('save_post', array($this, 'clear_post_cache'), 10, 2);
        add_action('deleted_post', array($this, 'clear_post_cache'));
    }
    
    /**
     * 获取缓存的摘要
     * @param int $post_id 文章ID
     * @return mixed 缓存的摘要或false
     */
    public function get_cached_excerpt($post_id) {
        $cache_key = $this->get_cache_key($post_id);
        $cached = wp_cache_get($cache_key, $this->cache_group);
        
        // 如果缓存存在且未过期,返回缓存内容
        if ($cached !== false && isset($cached['data'], $cached['expires'])) {
            if ($cached['expires'] > time()) {
                return $cached['data'];
            }
            // 缓存过期,清除
            wp_cache_delete($cache_key, $this->cache_group);
        }
        
        return false;
    }
    
    /**
     * 设置摘要缓存
     * @param int $post_id 文章ID
     * @param string $excerpt 摘要内容
     * @param int $expiration 过期时间(秒)
     */
    public function set_cached_excerpt($post_id, $excerpt, $expiration = null) {
        if ($expiration === null) {
            $expiration = $this->cache_expiration;
        }
        
        $cache_key = $this->get_cache_key($post_id);
        $cache_data = array(
            'data' => $excerpt,
            'expires' => time() + $expiration,
            'created' => time()
        );
        
        wp_cache_set($cache_key, $cache_data, $this->cache_group, $expiration);
    }
    
    /**
     * 清除文章摘要缓存
     * @param int $post_id 文章ID
     */
    public function clear_post_cache($post_id) {
        $cache_key = $this->get_cache_key($post_id);
        wp_cache_delete($cache_key, $this->cache_group);
        
        // 同时清除相关文章的缓存(如果有相关文章功能)
        $this->clear_related_cache($post_id);
    }
    
    /**
     * 批量清除缓存
     * @param array $post_ids 文章ID数组
     */
    public function clear_bulk_cache($post_ids) {
        foreach ($post_ids as $post_id) {
            $this->clear_post_cache($post_id);
        }
    }
    
    /**
     * 获取缓存统计信息
     * @return array 缓存统计
     */
    public function get_cache_stats() {
        global $wpdb;
        
        // 注意:wp_cache_get 不直接支持统计,这里使用替代方法
        $stats = array(
            'total_posts' => wp_count_posts()->publish,
            'cache_hits' => get_transient('fse_cache_hits') ?: 0,
            'cache_misses' => get_transient('fse_cache_misses') ?: 0,
            'cache_clears' => get_transient('fse_cache_clears') ?: 0
        );
        
        return $stats;
    }
    
    /**
     * 生成缓存键
     * @param int $post_id 文章ID
     * @return string 缓存键
     */
    private function get_cache_key($post_id) {
        $post = get_post($post_id);
        $modified = $post ? $post->post_modified : '';
        
        return 'excerpt_' . $post_id . '_' . md5($modified);
    }
}

// 修改摘要生成器类,加入缓存支持
class FSE_Excerpt_Generator_With_Cache extends FSE_Excerpt_Generator {
    
    private $cache_manager;
    
    public function __construct() {
        parent::__construct();
        $this->cache_manager = new FSE_Cache_Manager();
        
        // 覆盖父类的生成方法
        remove_filter('the_excerpt', array($this, 'generate_smart_excerpt'), 10);
        remove_filter('get_the_excerpt', array($this, 'generate_smart_excerpt'), 10);
        
        add_filter('the_excerpt', array($this, 'generate_cached_excerpt'), 10, 2);
        add_filter('get_the_excerpt', array($this, 'generate_cached_excerpt'), 10, 2);
    }
    
    /**
     * 生成带缓存的摘要
     */
    public function generate_cached_excerpt($excerpt, $post = null) {
        if (!empty($excerpt) && !$this->is_auto_generated_excerpt($excerpt, $post)) {
            return $excerpt;
        }
        
        $post = get_post($post);
        if (!$post) {
            return $excerpt;
        }
        
        // 尝试从缓存获取
        $cached_excerpt = $this->cache_manager->get_cached_excerpt($post->ID);
        
        if ($cached_excerpt !== false) {
            $this->increment_cache_stat('hits');
            return $cached_excerpt;
        }
        
        $this->increment_cache_stat('misses');
        
        // 生成新摘要
        $new_excerpt = parent::generate_smart_excerpt($excerpt, $post);
        
        // 存入缓存
        $this->cache_manager->set_cached_excerpt($post->ID, $new_excerpt);
        
        return $new_excerpt;
    }
    
    /**
     * 更新缓存统计
     */
    private function increment_cache_stat($type) {
        $transient_key = 'fse_cache_' . $type;
        $current = get_transient($transient_key) ?: 0;
        set_transient($transient_key, $current + 1, 86400);
    }
}

八、插件测试与部署

创建测试脚本

<?php
/**
 * 插件测试类
 */
class FSE_Plugin_Tester {
    
    public static function run_tests() {
        $tests = array(
            'test_excerpt_generation' => '测试摘要生成',
            'test_cache_functionality' => '测试缓存功能',
            'test_settings_saving' => '测试设置保存',
            'test_shortcode_output' => '测试短码输出'
        );
        
        $results = array();
        
        foreach ($tests as $method => $description) {
            try {
                $result = self::$method();
                $results[] = array(
                    'test' => $description,
                    'status' => $result ? '通过' : '失败',
                    'message' => $result ? '测试成功' : '测试失败'
                );
            } catch (Exception $e) {
                $results[] = array(
                    'test' => $description,
                    'status' => '错误',
                    'message' => $e->getMessage()
                );
            }
        }
        
        return $results;
    }
    
    /**
     * 测试摘要生成功能
     */
    private static function test_excerpt_generation() {
        // 创建测试文章
        $post_id = wp_insert_post(array(
            'post_title' => '测试文章 - ' . time(),
            'post_content' => '这是一个测试文章内容。智能摘要插件应该能够从这段文字中提取关键信息。'
                           . '第二句话包含了更多细节和描述。'
                           . '第三句话是文章的结论部分。',
            'post_status' => 'publish',
            'post_type' => 'post'
        ));
        
        $post = get_post($post_id);
        $generator = new FSE_Excerpt_Generator();
        $excerpt = $generator->generate_smart_excerpt('', $post);
        
        // 清理测试文章
        wp_delete_post($post_id, true);
        
        // 验证摘要生成
        return !empty($excerpt) && strlen($excerpt) > 0;
    }
    
    /**
     * 测试缓存功能
     */
    private static function test_cache_functionality() {
        $cache_manager = new FSE_Cache_Manager();
        $test_data = '测试缓存数据';
        $test_post_id = 99999; // 使用不存在的文章ID
        
        // 测试设置缓存
        $cache_manager->set_cached_excerpt($test_post_id, $test_data, 60);
        
        // 测试获取缓存
        $cached = $cache_manager->get_cached_excerpt($test_post_id);
        
        // 测试清除缓存
        $cache_manager->clear_post_cache($test_post_id);
        $after_clear = $cache_manager->get_cached_excerpt($test_post_id);
        
        return $cached === $test_data && $after_clear === false;
    }
}

// 在插件设置页面添加测试按钮
add_action('fse_settings_page_bottom', function() {
    if (isset($_GET['run_tests']) && current_user_can('manage_options')) {
        $results = FSE_Plugin_Tester::run_tests();
        ?>
        <div class="fse-test-results">
            <h3>插件测试结果</h3>
            <table class="widefat">
                <thead>
                    <tr>
                        <th>测试项目</th>
                        <th>状态</th>
                        <th>说明</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results as $result): ?>
                    <tr>
                        <td><?php echo esc_html($result['test']); ?></td>
                        <td>
                            <span class="fse-test-status fse-status-<?php echo esc_attr($result['status']); ?>">
                                <?php echo esc_html($result['status']); ?>
                            </span>
                        </td>
                        <td><?php echo esc_html($result['message']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php
    }
    
    // 添加测试按钮
    ?>
    <div class="fse-test-section">
        <h3>插件测试</h3>
        <p>运行插件功能测试以确保所有功能正常工作。</p>
        <a href="<?php echo esc_url(add_query_arg('run_tests', '1')); ?>" 
           class="button button-secondary">
            运行测试
        </a>
    </div>
    <?php
});

创建安装和卸载脚本

<?php
/**
 * 插件安装和卸载处理
 */
class FSE_Installer {
    
    /**
     * 插件激活时执行
     */
    public static function activate() {
        // 创建默认设置
        $default_settings = array(
            'excerpt_length' => 150,
            'extraction_method' => 'hybrid',
            'enable_cache' => true,
            'cache_expiration' => 86400,
            'post_types' => array('post'),
            'show_read_more' => true
        );
        
        if (!get_option('fse_settings')) {
            add_option('fse_settings', $default_settings);
        }
        
        // 创建数据库表(如果需要)
        self::create_database_tables();
        
        // 设置插件版本
        update_option('fse_version', FSE_VERSION);
        
        // 添加管理员通知
        set_transient('fse_activation_notice', true, 30);
    }
    
    /**
     * 插件卸载时执行
     */
    public static function uninstall() {
        // 删除设置
        delete_option('fse_settings');
        delete_option('fse_version');
        
        // 删除所有文章的自定义摘要
        global $wpdb;
        $wpdb->query(
            "DELETE FROM {$wpdb->postmeta} WHERE meta_key = '_fse_optimized_excerpt'"
        );
        
        // 清理缓存
        wp_cache_flush();
        
        // 删除临时数据
        delete_transient('fse_cache_hits');
        delete_transient('fse_cache_misses');
        delete_transient('fse_cache_clears');
    }
    
    /**
     * 创建数据库表
     */
    private static function create_database_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->prefix . 'fse_excerpt_logs';
        
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            excerpt_type varchar(50) NOT NULL,
            excerpt_text text NOT NULL,
            generated_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY excerpt_type (excerpt_type)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * 插件升级处理
     */
    public static function upgrade() {
        $current_version = get_option('fse_version', '1.0.0');
        
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/6034.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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