首页 / 教程文章 / 网络传媒WordPress柔性内容智能摘要与关键词提取插件教程

网络传媒WordPress柔性内容智能摘要与关键词提取插件教程

本教程介绍如何为WordPress开发一款柔性内容智能摘要与关键词提取插件。该插件利用自然语言处理技术,自动分析文章内容,生成精准摘要和核心关键词,支持自定义摘要长度与关键词数量,并提供手动调整功能。教程涵盖插件基础结构、核心类实现、管理界面集成及百度NLP API调用示例,帮助网络传媒高效处理海量内容,提升读者信息获取效率。

网络传媒WordPress柔性内容智能摘要与关键词提取插件教程

引言:为什么需要智能内容处理插件

在当今信息爆炸的时代,网络传媒网站每天产生大量内容,如何让读者快速获取文章核心信息成为关键挑战。手动编写摘要和关键词不仅耗时耗力,而且难以保持一致性。本教程将介绍如何为WordPress开发一个柔性内容智能摘要与关键词提取插件,利用自然语言处理技术自动分析文章内容,生成精准的摘要和关键词。

插件功能概述

本插件将实现以下核心功能:

  1. 自动分析文章内容,生成智能摘要
  2. 提取文章核心关键词
  3. 支持自定义摘要长度和关键词数量
  4. 提供手动调整功能
  5. 兼容多种文章类型

环境准备与插件基础结构

首先,我们需要创建插件的基本文件结构:

intelligent-content-analyzer/
├── intelligent-content-analyzer.php
├── includes/
│   ├── class-content-analyzer.php
│   ├── class-keyword-extractor.php
│   └── class-admin-interface.php
├── assets/
│   ├── css/
│   │   └── admin-style.css
│   └── js/
│       └── admin-script.js
└── languages/

主插件文件代码

<?php
/**
 * Plugin Name: 智能内容摘要与关键词提取器
 * Plugin URI:  https://yourwebsite.com/
 * Description: 自动为WordPress文章生成智能摘要和提取关键词
 * Version:     1.0.0
 * Author:      网络传媒开发者
 * License:     GPL v2 or later
 * Text Domain: intelligent-content-analyzer
 */

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

// 定义插件常量
define('ICA_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('ICA_PLUGIN_URL', plugin_dir_url(__FILE__));
define('ICA_VERSION', '1.0.0');

// 自动加载类文件
spl_autoload_register(function ($class) {
    $prefix = 'ICA_';
    $base_dir = ICA_PLUGIN_PATH . 'includes/';
    
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    
    $relative_class = substr($class, $len);
    $file = $base_dir . 'class-' . str_replace('_', '-', strtolower($relative_class)) . '.php';
    
    if (file_exists($file)) {
        require_once $file;
    }
});

// 初始化插件
function ica_init_plugin() {
    // 检查WordPress版本
    if (version_compare(get_bloginfo('version'), '5.0', '<')) {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>';
            echo '智能内容分析插件需要WordPress 5.0或更高版本';
            echo '</p></div>';
        });
        return;
    }
    
    // 初始化核心组件
    $content_analyzer = new ICA_Content_Analyzer();
    $keyword_extractor = new ICA_Keyword_Extractor();
    $admin_interface = new ICA_Admin_Interface($content_analyzer, $keyword_extractor);
    
    // 注册激活和停用钩子
    register_activation_hook(__FILE__, ['ICA_Admin_Interface', 'activate_plugin']);
    register_deactivation_hook(__FILE__, ['ICA_Admin_Interface', 'deactivate_plugin']);
}

add_action('plugins_loaded', 'ica_init_plugin');

核心内容分析类实现

智能摘要生成器

<?php
/**
 * 内容分析器类 - 负责生成智能摘要
 */
class ICA_Content_Analyzer {
    
    private $summary_length = 150; // 默认摘要长度
    
    /**
     * 设置摘要长度
     * @param int $length 摘要长度
     */
    public function set_summary_length($length) {
        $this->summary_length = max(50, intval($length));
    }
    
    /**
     * 生成智能摘要
     * @param string $content 文章内容
     * @return string 生成的摘要
     */
    public function generate_summary($content) {
        // 清理HTML标签,保留文本内容
        $clean_content = wp_strip_all_tags($content);
        
        // 移除短代码
        $clean_content = strip_shortcodes($clean_content);
        
        // 如果内容已经足够短,直接返回
        if (mb_strlen($clean_content) <= $this->summary_length) {
            return $clean_content;
        }
        
        // 分割成句子
        $sentences = $this->split_into_sentences($clean_content);
        
        // 计算句子权重
        $weighted_sentences = $this->calculate_sentence_weights($sentences);
        
        // 选择权重最高的句子
        $selected_sentences = $this->select_top_sentences($weighted_sentences);
        
        // 按原文顺序排序并生成摘要
        return $this->construct_summary($selected_sentences, $sentences);
    }
    
    /**
     * 将内容分割成句子
     * @param string $text 文本内容
     * @return array 句子数组
     */
    private function split_into_sentences($text) {
        // 使用正则表达式分割句子
        $pattern = '/(?<=[.!?。!?])s+/u';
        $sentences = preg_split($pattern, $text, -1, PREG_SPLIT_NO_EMPTY);
        
        // 过滤空句子
        return array_filter($sentences, function($sentence) {
            return trim($sentence) !== '';
        });
    }
    
    /**
     * 计算句子权重
     * @param array $sentences 句子数组
     * @return array 带权重的句子
     */
    private function calculate_sentence_weights($sentences) {
        $weights = [];
        
        foreach ($sentences as $index => $sentence) {
            $weight = 0;
            
            // 规则1:位置权重(开头和结尾的句子更重要)
            if ($index === 0) $weight += 3;
            if ($index === count($sentences) - 1) $weight += 2;
            
            // 规则2:长度权重(中等长度的句子更好)
            $length = mb_strlen($sentence);
            if ($length > 30 && $length < 100) $weight += 2;
            
            // 规则3:关键词密度(包含重要词汇)
            $keywords = ['因为', '所以', '然而', '因此', '总结', '总之', '重要的是'];
            foreach ($keywords as $keyword) {
                if (mb_strpos($sentence, $keyword) !== false) {
                    $weight += 1;
                }
            }
            
            $weights[$index] = $weight;
        }
        
        return $weights;
    }
    
    /**
     * 选择权重最高的句子
     * @param array $weighted_sentences 带权重的句子
     * @return array 选中的句子索引
     */
    private function select_top_sentences($weighted_sentences) {
        arsort($weighted_sentences);
        
        $selected = [];
        $total_length = 0;
        
        foreach ($weighted_sentences as $index => $weight) {
            // 这里需要获取句子长度,实际实现中需要传递句子数组
            // 简化处理:选择前3个权重最高的句子
            if (count($selected) < 3) {
                $selected[] = $index;
            } else {
                break;
            }
        }
        
        sort($selected); // 按原文顺序排序
        return $selected;
    }
    
    /**
     * 构建摘要
     * @param array $selected_indices 选中的句子索引
     * @param array $sentences 所有句子
     * @return string 生成的摘要
     */
    private function construct_summary($selected_indices, $sentences) {
        $summary_parts = [];
        
        foreach ($selected_indices as $index) {
            if (isset($sentences[$index])) {
                $summary_parts[] = $sentences[$index];
            }
        }
        
        $summary = implode(' ', $summary_parts);
        
        // 确保摘要不超过指定长度
        if (mb_strlen($summary) > $this->summary_length) {
            $summary = mb_substr($summary, 0, $this->summary_length) . '...';
        }
        
        return $summary;
    }
}

关键词提取器

<?php
/**
 * 关键词提取器类 - 负责从内容中提取关键词
 */
class ICA_Keyword_Extractor {
    
    private $stop_words = [
        '的', '了', '在', '是', '我', '有', '和', '就',
        '不', '人', '都', '一', '一个', '上', '也', '很',
        '到', '说', '要', '去', '你', '会', '着', '没有',
        '看', '好', '自己', '这', '那', '这个', '那个'
    ];
    
    private $max_keywords = 5; // 默认最大关键词数量
    
    /**
     * 设置最大关键词数量
     * @param int $count 关键词数量
     */
    public function set_max_keywords($count) {
        $this->max_keywords = max(1, min(10, intval($count)));
    }
    
    /**
     * 从内容中提取关键词
     * @param string $content 文章内容
     * @return array 关键词数组
     */
    public function extract_keywords($content) {
        // 清理内容
        $clean_content = wp_strip_all_tags($content);
        $clean_content = strip_shortcodes($clean_content);
        
        // 分词处理
        $words = $this->segment_text($clean_content);
        
        // 过滤停用词
        $filtered_words = $this->filter_stop_words($words);
        
        // 计算词频
        $word_frequencies = array_count_values($filtered_words);
        
        // 按频率排序
        arsort($word_frequencies);
        
        // 选择最高频的词作为关键词
        $keywords = array_slice(array_keys($word_frequencies), 0, $this->max_keywords);
        
        return $keywords;
    }
    
    /**
     * 文本分词
     * @param string $text 文本内容
     * @return array 词语数组
     */
    private function segment_text($text) {
        // 简化版分词:按标点和空格分割
        // 实际应用中应使用专业分词库,如jieba-php
        
        // 移除所有标点符号
        $text = preg_replace('/[[:punct:]]/u', ' ', $text);
        
        // 分割成词语
        $words = preg_split('/s+/u', $text, -1, PREG_SPLIT_NO_EMPTY);
        
        // 过滤单字词(中文中单字通常不是关键词)
        $filtered_words = array_filter($words, function($word) {
            return mb_strlen($word) > 1;
        });
        
        return array_values($filtered_words);
    }
    
    /**
     * 过滤停用词
     * @param array $words 词语数组
     * @return array 过滤后的词语
     */
    private function filter_stop_words($words) {
        return array_filter($words, function($word) {
            return !in_array($word, $this->stop_words);
        });
    }
    
    /**
     * 添加自定义停用词
     * @param array $words 停用词数组
     */
    public function add_stop_words($words) {
        $this->stop_words = array_merge($this->stop_words, (array)$words);
        $this->stop_words = array_unique($this->stop_words);
    }
}

管理界面与集成

WordPress管理界面集成

<?php
/**
 * 管理界面类 - 处理插件设置和文章编辑界面集成
 */
class ICA_Admin_Interface {
    
    private $content_analyzer;
    private $keyword_extractor;
    
    public function __construct($content_analyzer, $keyword_extractor) {
        $this->content_analyzer = $content_analyzer;
        $this->keyword_extractor = $keyword_extractor;
        
        $this->init_hooks();
    }
    
    /**
     * 初始化WordPress钩子
     */
    private function init_hooks() {
        // 添加文章编辑框的元框
        add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
        
        // 保存文章时处理摘要和关键词
        add_action('save_post', [$this, 'save_post_analysis'], 10, 2);
        
        // 添加设置菜单
        add_action('admin_menu', [$this, 'add_admin_menu']);
        
        // 注册设置
        add_action('admin_init', [$this, 'register_settings']);
        
        // 添加快速编辑支持
        add_action('quick_edit_custom_box', [$this, 'add_quick_edit_fields'], 10, 2);
    }
    
    /**
     * 添加元框到文章编辑页面
     */
    public function add_meta_boxes() {
        add_meta_box(
            'ica_content_analysis',
            '智能内容分析',
            [$this, 'render_meta_box'],
            'post',
            'side',
            'high'
        );
    }
    
    /**
     * 渲染元框内容
     * @param WP_Post $post 当前文章对象
     */
    public function render_meta_box($post) {
        // 添加安全验证
        wp_nonce_field('ica_save_analysis', 'ica_analysis_nonce');
        
        // 获取现有数据
        $current_summary = get_post_meta($post->ID, '_ica_auto_summary', true);
        $current_keywords = get_post_meta($post->ID, '_ica_auto_keywords', true);
        
        if (empty($current_keywords)) {
            $current_keywords = [];
        }
        
        ?>
        <div class="ica-analysis-container">
            <p>
                <label for="ica_auto_summary">智能摘要:</label>
                <textarea id="ica_auto_summary" 
                          name="ica_auto_summary" 
                          rows="4" 
                          style="width:100%;"><?php echo esc_textarea($current_summary); ?></textarea>
            </p>
            
            <p>
                <label for="ica_auto_keywords">关键词 (用逗号分隔):</label>
                <input type="text" 
                       id="ica_auto_keywords" 
                       name="ica_auto_keywords" 
                       style="width:100%;" 
                       value="<?php echo esc_attr(implode(', ', $current_keywords)); ?>">
            </p>
            
            <p>
                <button type="button" 
                        id="ica_analyze_content" 
                        class="button button-secondary">
                    重新分析内容
                </button>
                <span class="spinner" style="float:none;"></span>
            </p>
            
            <p class="description">
                点击"重新分析内容"按钮将根据当前文章内容自动生成摘要和关键词。
            </p>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('#ica_analyze_content').on('click', function() {
                var $button = $(this);
                var $spinner = $button.next('.spinner');
                
                $spinner.addClass('is-active');
                
                // 获取文章内容
                var content = '';
                if (typeof tinymce !== 'undefined' && tinymce.get('content')) {
                    content = tinymce.get('content').getContent();
                } else {
                    content = $('#content').val();
                }
                
                // 发送AJAX请求
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'ica_analyze_content',
                        content: content,
                        post_id: <?php echo $post->ID; ?>,
                        nonce: '<?php echo wp_create_nonce("ica_ajax_analysis"); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#ica_auto_summary').val(response.data.summary);
                            $('#ica_auto_keywords').val(response.data.keywords.join(', '));
                        } else {
                            alert('分析失败: ' + response.data);
                        }
                        $spinner.removeClass('is-active');
                    },
                    error: function() {
                        alert('请求失败,请重试');
                        $spinner.removeClass('is-active');
                    }
                });
            });
        });
        </script>
        <?php
    }
    
    /**
     * 保存文章分析数据
     * @param int $post_id 文章ID
     * @param WP_Post $post 文章对象
     */
    public function save_post_analysis($post_id, $post) {
        // 检查自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 验证nonce
        if (!isset($_POST['ica_analysis_nonce']) || 
            !wp_verify_nonce($_POST['ica_analysis_nonce'], 'ica_save_analysis')) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 保存摘要
        if (isset($_POST['ica_auto_summary'])) {
            update_post_meta($post_id, '_ica_auto_summary', sanitize_textarea_field($_POST['ica_auto_summary']));
        }
        
        // 保存关键词
        if (isset($_POST['ica_auto_keywords'])) {
            $keywords = array_map('trim', explode(',', $_POST['ica_auto_keywords']));
            $keywords = array_filter($keywords); // 移除空值
    }
    
    // 如果摘要为空,自动生成
    if (empty($_POST['ica_auto_summary']) && $post->post_status === 'publish') {
        $this->auto_generate_analysis($post_id, $post);
    }
}

/**
 * 自动生成分析结果
 * @param int $post_id 文章ID
 * @param WP_Post $post 文章对象
 */
private function auto_generate_analysis($post_id, $post) {
    // 获取设置
    $auto_generate = get_option('ica_auto_generate', 'yes');
    
    if ($auto_generate === 'yes') {
        // 生成摘要
        $summary = $this->content_analyzer->generate_summary($post->post_content);
        update_post_meta($post_id, '_ica_auto_summary', $summary);
        
        // 提取关键词
        $keywords = $this->keyword_extractor->extract_keywords($post->post_content);
        update_post_meta($post_id, '_ica_auto_keywords', $keywords);
    }
}

/**
 * 添加管理菜单
 */
public function add_admin_menu() {
    add_options_page(
        '智能内容分析设置',
        '内容分析',
        'manage_options',
        'ica-settings',
        [$this, 'render_settings_page']
    );
}

/**
 * 渲染设置页面
 */
public function render_settings_page() {
    ?>
    <div class="wrap">
        <h1>智能内容分析设置</h1>
        
        <form method="post" action="options.php">
            <?php
            settings_fields('ica_settings_group');
            do_settings_sections('ica-settings');
            submit_button();
            ?>
        </form>
        
        <div class="ica-tools-section">
            <h2>批量处理工具</h2>
            <p>
                <button type="button" id="ica_batch_process" class="button button-primary">
                    批量处理所有文章
                </button>
                <span class="spinner" style="float:none;"></span>
            </p>
            <p class="description">
                这将为所有已发布文章生成智能摘要和关键词(可能需要较长时间)。
            </p>
            <div id="ica_batch_progress" style="display:none;">
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
                <p class="progress-text">处理中: <span class="processed">0</span>/<span class="total">0</span></p>
            </div>
        </div>
    </div>
    
    <style>
    .progress-bar {
        width: 100%;
        height: 20px;
        background: #f1f1f1;
        border-radius: 3px;
        margin: 10px 0;
    }
    .progress-fill {
        height: 100%;
        background: #0073aa;
        border-radius: 3px;
        width: 0%;
        transition: width 0.3s;
    }
    </style>
    
    <script>
    jQuery(document).ready(function($) {
        $('#ica_batch_process').on('click', function() {
            var $button = $(this);
            var $spinner = $button.next('.spinner');
            var $progress = $('#ica_batch_progress');
            var $progressFill = $progress.find('.progress-fill');
            var $processed = $progress.find('.processed');
            var $total = $progress.find('.total');
            
            $button.prop('disabled', true);
            $spinner.addClass('is-active');
            $progress.show();
            
            // 获取文章总数
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ica_get_post_count',
                    nonce: '<?php echo wp_create_nonce("ica_batch_process"); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        var total = response.data.total;
                        var processed = 0;
                        $total.text(total);
                        $processed.text(processed);
                        
                        // 开始批量处理
                        processBatch(0, total);
                    }
                }
            });
            
            function processBatch(offset, total) {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'ica_process_batch',
                        offset: offset,
                        nonce: '<?php echo wp_create_nonce("ica_batch_process"); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            processed += response.data.processed;
                            $processed.text(processed);
                            
                            var progressPercent = (processed / total) * 100;
                            $progressFill.css('width', progressPercent + '%');
                            
                            if (response.data.completed) {
                                // 处理完成
                                $button.prop('disabled', false);
                                $spinner.removeClass('is-active');
                                alert('批量处理完成!共处理 ' + processed + ' 篇文章。');
                            } else {
                                // 继续处理下一批
                                processBatch(offset + response.data.processed, total);
                            }
                        }
                    }
                });
            }
        });
    });
    </script>
    <?php
}

/**
 * 注册设置
 */
public function register_settings() {
    register_setting('ica_settings_group', 'ica_auto_generate');
    register_setting('ica_settings_group', 'ica_summary_length');
    register_setting('ica_settings_group', 'ica_max_keywords');
    
    add_settings_section(
        'ica_main_settings',
        '主要设置',
        null,
        'ica-settings'
    );
    
    add_settings_field(
        'ica_auto_generate',
        '自动生成',
        [$this, 'render_auto_generate_field'],
        'ica-settings',
        'ica_main_settings'
    );
    
    add_settings_field(
        'ica_summary_length',
        '摘要长度',
        [$this, 'render_summary_length_field'],
        'ica-settings',
        'ica_main_settings'
    );
    
    add_settings_field(
        'ica_max_keywords',
        '关键词数量',
        [$this, 'render_max_keywords_field'],
        'ica-settings',
        'ica_main_settings'
    );
}

/**
 * 渲染自动生成字段
 */
public function render_auto_generate_field() {
    $value = get_option('ica_auto_generate', 'yes');
    ?>
    <select name="ica_auto_generate">
        <option value="yes" <?php selected($value, 'yes'); ?>>是</option>
        <option value="no" <?php selected($value, 'no'); ?>>否</option>
    </select>
    <p class="description">发布文章时自动生成摘要和关键词</p>
    <?php
}

/**
 * 渲染摘要长度字段
 */
public function render_summary_length_field() {
    $value = get_option('ica_summary_length', 150);
    ?>
    <input type="number" name="ica_summary_length" value="<?php echo esc_attr($value); ?>" min="50" max="500">
    <p class="description">摘要的最大字符数(50-500)</p>
    <?php
}

/**
 * 渲染关键词数量字段
 */
public function render_max_keywords_field() {
    $value = get_option('ica_max_keywords', 5);
    ?>
    <input type="number" name="ica_max_keywords" value="<?php echo esc_attr($value); ?>" min="1" max="10">
    <p class="description">提取的关键词数量(1-10)</p>
    <?php
}

/**
 * 插件激活时的操作
 */
public static function activate_plugin() {
    // 创建必要的数据库表或选项
    add_option('ica_auto_generate', 'yes');
    add_option('ica_summary_length', 150);
    add_option('ica_max_keywords', 5);
    
    // 设置默认停用词
    $default_stop_words = [
        '的', '了', '在', '是', '我', '有', '和', '就',
        '不', '人', '都', '一', '一个', '上', '也', '很',
        '到', '说', '要', '去', '你', '会', '着', '没有',
        '看', '好', '自己', '这', '那', '这个', '那个'
    ];
    add_option('ica_stop_words', $default_stop_words);
}

/**
 * 插件停用时的操作
 */
public static function deactivate_plugin() {
    // 清理临时数据
    // 注意:这里不删除设置,以便重新激活时保留配置
}

}


## AJAX处理与前端交互

### AJAX处理器

<?php
/**

  • AJAX处理器 - 处理前端请求
    */

class ICA_Ajax_Handler {


private $content_analyzer;
private $keyword_extractor;

public function __construct($content_analyzer, $keyword_extractor) {
    $this->content_analyzer = $content_analyzer;
    $this->keyword_extractor = $keyword_extractor;
    
    $this->init_ajax_handlers();
}

/**
 * 初始化AJAX处理器
 */
private function init_ajax_handlers() {
    // 内容分析请求
    add_action('wp_ajax_ica_analyze_content', [$this, 'handle_analyze_content']);
    
    // 批量处理相关
    add_action('wp_ajax_ica_get_post_count', [$this, 'handle_get_post_count']);
    add_action('wp_ajax_ica_process_batch', [$this, 'handle_process_batch']);
}

/**
 * 处理内容分析请求
 */
public function handle_analyze_content() {
    // 验证nonce
    if (!wp_verify_nonce($_POST['nonce'], 'ica_ajax_analysis')) {
        wp_die('安全验证失败');
    }
    
    // 获取内容
    $content = isset($_POST['content']) ? $_POST['content'] : '';
    
    if (empty($content)) {
        wp_send_json_error('内容为空');
    }
    
    // 应用设置
    $summary_length = get_option('ica_summary_length', 150);
    $max_keywords = get_option('ica_max_keywords', 5);
    
    $this->content_analyzer->set_summary_length($summary_length);
    $this->keyword_extractor->set_max_keywords($max_keywords);
    
    // 生成摘要和关键词
    $summary = $this->content_analyzer->generate_summary($content);
    $keywords = $this->keyword_extractor->extract_keywords($content);
    
    wp_send_json_success([
        'summary' => $summary,
        'keywords' => $keywords
    ]);
}

/**
 * 获取文章总数
 */
public function handle_get_post_count() {
    if (!current_user_can('edit_posts')) {
        wp_die('权限不足');
    }
    
    $count = wp_count_posts('post');
    $total = $count->publish;
    
    wp_send_json_success(['total' => $total]);
}

/**
 * 处理批量请求
 */
public function handle_process_batch() {
    if (!current_user_can('edit_posts')) {
        wp_die('权限不足');
    }
    
    $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
    $batch_size = 10; // 每批处理10篇文章
    
    // 获取文章
    $posts = get_posts([
        'post_type' => 'post',
        'post_status' => 'publish',
        'numberposts' => $batch_size,
        'offset' => $offset,
        'orderby' => 'ID',
        'order' => 'ASC'
    ]);
    
    $processed = 0;
    
    foreach ($posts as $post) {
        // 检查是否已有摘要
        $existing_summary = get_post_meta($post->ID, '_ica_auto_summary', true);
        
        if (empty($existing_summary)) {
            // 生成摘要
            $summary = $this->content_analyzer->generate_summary($post->post_content);
            update_post_meta($post->ID, '_ica_auto_summary', $summary);
            
            // 提取关键词
            $keywords = $this->keyword_extractor->extract_keywords($post->post_content);
            update_post_meta($post->ID, '_ica_auto_keywords', $keywords);
        }
        
        $processed++;
    }
    
    $completed = ($offset + $processed) >= wp_count_posts('post')->publish;
    
    wp_send_json_success([
        'processed' => $processed,
        'completed' => $completed
    ]);
}

}


## 模板函数与主题集成

### 主题模板函数

<?php
/**

  • 模板函数 - 供主题开发者使用
    */

/**

  • 获取文章的智能摘要
  • @param int $post_id 文章ID,默认为当前文章
  • @return string 文章摘要
    */

function ica_get_auto_summary($post_id = null) {

if (!$post_id) {
    $post_id = get_the_ID();
}

$summary = get_post_meta($post_id, '_ica_auto_summary', true);

// 如果没有摘要,尝试生成一个
if (empty($summary)) {
    $post = get_post($post_id);
    if ($post) {
        $analyzer = new ICA_Content_Analyzer();
        $summary = $analyzer->generate_summary($post->post_content);
        
        // 保存起来供下次使用
        update_post_meta($post_id, '_ica_auto_summary', $summary);
    }
}

return apply_filters('ica_auto_summary', $summary, $post_id);

}

/**

  • 获取文章的关键词
  • @param int $post_id 文章ID,默认为当前文章
  • @return array 关键词数组
    */

function ica_get_auto_keywords($post_id = null) {

if (!$post_id) {
    $post_id = get_the_ID();
}

$keywords = get_post_meta($post_id, '_ica_auto_keywords', true);

// 如果没有关键词,尝试提取
if (empty($keywords)) {
    $post = get_post($post_id);
    if ($post) {
        $extractor = new ICA_Keyword_Extractor();
        $keywords = $extractor->extract_keywords($post->post_content);
        
        // 保存起来供下次使用
        update_post_meta($post_id, '_ica_auto_keywords', $keywords);
    }
}

if (!is_array($keywords)) {
    $keywords = [];
}

return apply_filters('ica_auto_keywords', $keywords, $post_id);

}

/**

  • 显示文章摘要
  • @param int $post_id 文章ID
    */

function ica_display_auto_summary($post_id = null) {

$summary = ica_get_auto_summary($post_id);
if (!empty($summary)) {
    echo '<div class="ica-auto-summary">';
    echo '<h3>文章摘要</h3>';
    echo '<p>' . esc_html($summary) . '</p>';
    echo '</div>';
}

}

/**

  • 显示文章关键词
  • @param int $post_id 文章ID
    */

function ica_display_auto_keywords($post_id = null) {

$keywords = ica_get_auto_keywords($post_id);
if (!empty($keywords)) {
    echo '<div class="ica-auto-keywords">';
    echo '<h3>关键词</h3>';
    echo '<div class="keyword-tags">';
    foreach ($keywords as $keyword) {
        echo '<span class="keyword-tag">' . esc_html($keyword) . '</span> ';
    }
    echo '</div>';
    echo '</div>';
}

}

/**

  • 在文章内容前自动添加摘要
  • @param string $content 文章内容
  • @return string 添加摘要后的内容
    */

function ica_add_summary_to_content($content) {

if (is_single() && in_the_loop() && is_main_query()) {
    $auto_insert = get_option('ica_auto_insert_summary', 'no');
    
    if ($auto_insert === 'yes') {
        $summary = ica_get_auto_summary();
        if (!empty($summary)) {
            $summary_html = '<div class="ica-content-summary"><strong>文章摘要:</strong>' . 
                           esc_html($summary) . '</div>';
            $content = $summary_html . $content;
        }
    }
}

return $content;

}
add_filter('the_content', 'ica_add_summary_to_content');


## 插件优化与扩展建议

### 性能优化

1. **缓存机制**:为频繁访问的文章分析结果添加缓存
2. **异步处理**:对于长文章使用后台任务处理
3. **数据库索引**:为文章元数据添加适当索引

### 功能扩展

1. **多语言支持**:添加对英文、日文等其他语言的支持
2. **情感分析**:集成情感分析功能
3. **关键词云**:生成可视化关键词云图
4. **SEO优化**:自动生成meta description和keywords标签
5. **社交媒体摘要**:为不同平台生成定制化摘要

### 集成第三方服务

/**

  • 百度NLP API集成示例
    */

class ICA_Baidu_NLP_Integration {


private $api_key;
private $secret_key;

public function __construct($api_key, $secret_key) {
    $this->api_key = $api_key;
    $this->secret_key = $secret_key;
}

/**
 * 使用百度NLP提取关键词
 */
public function extract_keywords_with_baidu($content) {
    // 获取access token
    $token = $this->get_access_token();
    
    // 调用关键词提取API
    $url = "https://aip.baidubce.com/rpc/2.0/nlp/v1
本文来自网络投稿,不代表本站点的立场,转载请注明出处:https://www.gongxiangcang.com/6611.html

溯源库®作者

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

为您推荐

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@suyuanku.com

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

微信扫一扫关注我们

返回顶部