首页 / 教程文章 / 网络传媒WordPress柔性内容智能排版插件应用详解

网络传媒WordPress柔性内容智能排版插件应用详解

网络传媒WordPress柔性内容智能排版插件应用详解

引言:智能排版的时代需求

在数字化内容爆炸的时代,网络传媒机构面临着前所未有的排版挑战。每天需要处理大量文章、新闻稿、专题报道等内容,传统的手动排版方式已无法满足高效、统一、美观的发布需求。WordPress作为全球最流行的内容管理系统,其插件生态为解决这一问题提供了可能。柔性内容智能排版插件正是为此而生,它通过智能算法和可配置规则,实现了内容排版的自动化与个性化平衡。

一、智能排版插件的核心功能解析

1.1 自适应内容识别

智能排版插件能够自动识别不同类型的内容元素,包括标题、段落、图片、引用、代码块等,并根据预设规则进行差异化处理。

/**
 * 内容元素识别与分类函数
 * @param string $content 原始内容
 * @return array 分类后的内容元素
 */
function intelligent_content_parser($content) {
    $elements = array();
    
    // 使用正则表达式匹配不同内容类型
    $patterns = array(
        'heading' => '/<h[1-6][^>]*>.*?</h[1-6]>/is',
        'paragraph' => '/<p[^>]*>.*?</p>/is',
        'image' => '/<img[^>]+>/i',
        'blockquote' => '/<blockquote[^>]*>.*?</blockquote>/is',
        'code' => '/<pre[^>]*>.*?</pre>|<code[^>]*>.*?</code>/is'
    );
    
    foreach ($patterns as $type => $pattern) {
        preg_match_all($pattern, $content, $matches);
        if (!empty($matches[0])) {
            $elements[$type] = $matches[0];
        }
    }
    
    // 返回结构化内容数据
    return apply_filters('parsed_content_elements', $elements, $content);
}

// 使用示例
$article_content = get_the_content();
$parsed_elements = intelligent_content_parser($article_content);

1.2 动态布局调整

基于内容长度、元素类型和用户设备,插件能够动态调整页面布局,确保最佳阅读体验。

二、插件安装与基础配置

2.1 安装步骤

  1. 登录WordPress后台,进入"插件"→"安装插件"
  2. 搜索"Flexible Content Layout"或上传插件压缩包
  3. 激活插件并完成初始设置

2.2 基础配置代码示例

/**
 * 智能排版插件初始化配置
 * 此代码可添加到主题的functions.php或插件配置页面
 */
function flexible_content_plugin_setup() {
    // 默认排版配置
    $default_config = array(
        'responsive_breakpoints' => array(
            'mobile' => 768,
            'tablet' => 1024,
            'desktop' => 1200
        ),
        'typography_presets' => array(
            'news_article' => array(
                'font_size' => '16px',
                'line_height' => 1.6,
                'paragraph_spacing' => '1.5em'
            ),
            'feature_story' => array(
                'font_size' => '18px',
                'line_height' => 1.8,
                'paragraph_spacing' => '2em'
            )
        ),
        'auto_optimize_images' => true,
        'lazy_loading_enabled' => true,
        'content_priority' => array('text', 'images', 'multimedia')
    );
    
    // 保存配置到数据库
    update_option('flexible_content_config', $default_config);
    
    // 初始化自定义CSS变量
    $css_variables = ":root {
        --content-font-size: " . $default_config['typography_presets']['news_article']['font_size'] . ";
        --content-line-height: " . $default_config['typography_presets']['news_article']['line_height'] . ";
        --reading-width: 65ch;
    }";
    
    wp_add_inline_style('flexible-content-main', $css_variables);
}
add_action('init', 'flexible_content_plugin_setup');

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

3.1 创建自定义排版模板

/**
 * 注册自定义内容模板
 * 允许编辑为不同类型的内容创建专属排版模板
 */
function register_content_templates() {
    $templates = array(
        'interview_layout' => array(
            'name' => '专访布局',
            'description' => '适用于人物专访的特殊排版',
            'structure' => array(
                'header' => array('featured_image', 'title', 'metadata'),
                'body' => array('intro', 'qna_section', 'pull_quotes'),
                'sidebar' => array('related_interviews', 'author_bio')
            ),
            'styles' => array(
                'qna_question' => array(
                    'font_weight' => 'bold',
                    'color' => '#2c3e50',
                    'margin_bottom' => '0.5em'
                ),
                'qna_answer' => array(
                    'padding_left' => '2em',
                    'border_left' => '3px solid #3498db'
                )
            )
        ),
        'news_brief' => array(
            'name' => '新闻简讯',
            'description' => '适用于短新闻的紧凑排版',
            'structure' => array('title', 'excerpt', 'read_more'),
            'styles' => array(
                'container' => array('max_width' => '600px', 'margin' => '0 auto')
            )
        )
    );
    
    // 将模板保存到数据库
    foreach ($templates as $slug => $template) {
        add_option('content_template_' . $slug, $template);
    }
    
    return $templates;
}

/**
 * 应用模板到内容
 * @param string $content 原始内容
 * @param string $template_slug 模板标识
 * @return string 处理后的内容
 */
function apply_content_template($content, $template_slug) {
    $template = get_option('content_template_' . $template_slug);
    
    if (!$template) {
        return $content;
    }
    
    // 根据模板结构重组内容
    $structured_content = '';
    
    foreach ($template['structure'] as $section => $elements) {
        $structured_content .= '<div class="content-section ' . $section . '">';
        
        foreach ($elements as $element) {
            $structured_content .= apply_filters(
                'render_content_element', 
                $content, 
                $element, 
                $template['styles']
            );
        }
        
        $structured_content .= '</div>';
    }
    
    // 添加模板特定样式
    $structured_content .= '<style>';
    foreach ($template['styles'] as $selector => $styles) {
        $structured_content .= '.' . $selector . ' {';
        foreach ($styles as $property => $value) {
            $structured_content .= str_replace('_', '-', $property) . ': ' . $value . ';';
        }
        $structured_content .= '}';
    }
    $structured_content .= '</style>';
    
    return $structured_content;
}

3.2 智能图片排版系统

/**
 * 智能图片排版处理
 * 根据图片尺寸、方向和上下文自动选择最佳布局
 */
function intelligent_image_layout($image_id, $context = 'inline') {
    $image_data = wp_get_attachment_metadata($image_id);
    $image_url = wp_get_attachment_url($image_id);
    $caption = wp_get_attachment_caption($image_id);
    
    // 计算图片宽高比
    $aspect_ratio = $image_data['width'] / $image_data['height'];
    
    // 根据宽高比和上下文确定布局
    $layout_class = 'image-';
    
    if ($aspect_ratio > 1.5) {
        $layout_class .= 'landscape';
        $max_width = '100%';
    } elseif ($aspect_ratio < 0.8) {
        $layout_class .= 'portrait';
        $max_width = '60%';
    } else {
        $layout_class .= 'square';
        $max_width = '80%';
    }
    
    // 添加上下文类
    $layout_class .= ' context-' . $context;
    
    // 生成响应式图片标记
    $image_html = '<figure class="intelligent-image ' . $layout_class . '" style="max-width: ' . $max_width . '">';
    $image_html .= '<img src="' . $image_url . '" 
                        alt="' . get_post_meta($image_id, '_wp_attachment_image_alt', true) . '"
                        loading="lazy"
                        data-width="' . $image_data['width'] . '"
                        data-height="' . $image_data['height'] . '">';
    
    if ($caption) {
        $image_html .= '<figcaption>' . $caption . '</figcaption>';
    }
    
    $image_html .= '</figure>';
    
    // 添加自适应样式
    $image_html .= '<style>
        .intelligent-image.landscape { float: none; margin: 1em auto; }
        .intelligent-image.portrait { float: right; margin: 0 0 1em 1em; }
        .intelligent-image.square { float: left; margin: 0 1em 1em 0; }
        
        @media (max-width: 768px) {
            .intelligent-image { float: none !important; max-width: 100% !important; }
        }
    </style>';
    
    return $image_html;
}

四、实战应用案例

4.1 新闻门户网站的应用

某大型新闻门户网站使用智能排版插件后,编辑效率提升了40%。通过预设的"突发新闻"、"深度报道"、"图片新闻"等模板,编辑只需选择内容类型,系统即可自动应用合适的排版规则。

4.2 多媒体内容集成

插件支持视频、音频、交互式图表等多媒体内容的智能嵌入。通过以下代码,可以实现多媒体内容的响应式布局:

/**
 * 多媒体内容智能嵌入
 * 自动检测媒体类型并应用最佳展示方式
 */
function smart_media_embed($url, $content_type = 'auto') {
    // 检测媒体类型
    if ($content_type === 'auto') {
        $content_type = detect_media_type($url);
    }
    
    $embed_html = '';
    
    switch ($content_type) {
        case 'video':
            $embed_html = '<div class="responsive-media video-container">';
            $embed_html .= wp_oembed_get($url);
            $embed_html .= '</div>';
            break;
            
        case 'audio':
            $embed_html = '<div class="responsive-media audio-container">';
            $embed_html .= wp_audio_shortcode(array('src' => $url));
            $embed_html .= '</div>';
            break;
            
        case 'interactive':
            $embed_html = '<div class="interactive-content" data-url="' . esc_url($url) . '">';
            $embed_html .= '<p>交互式内容加载中...</p>';
            $embed_html .= '</div>';
            break;
    }
    
    // 添加响应式媒体样式
    $embed_html .= '<style>
        .responsive-media {
            position: relative;
            padding-bottom: 56.25%; /* 16:9 宽高比 */
            height: 0;
            overflow: hidden;
            margin: 1.5em 0;
        }
        
        .responsive-media iframe,
        .responsive-media audio {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    </style>';
    
    return $embed_html;
}

五、性能优化与最佳实践

5.1 缓存策略实现

智能排版处理可能增加服务器负载,合理的缓存机制至关重要:

/**
 * 排版结果缓存系统
 * 避免重复处理相同内容
 */
class ContentLayoutCache {
    private $cache_group = 'content_layout';
    private $expiration = 3600; // 1小时
    
    public function get_cached_layout($content_hash, $template_id) {
        $cache_key = $this->generate_cache_key($content_hash, $template_id);
        $cached = wp_cache_get($cache_key, $this->cache_group);
        
        if ($cached !== false) {
            return $cached;
        }
        
        return false;
    }
    
    public function cache_layout($content_hash, $template_id, $formatted_content) {
        $cache_key = $this->generate_cache_key($content_hash, $template_id);
        wp_cache_set($cache_key, $formatted_content, $this->cache_group, $this->expiration);
    }
    
    private function generate_cache_key($content_hash, $template_id) {
        return 'layout_' . $content_hash . '_' . $template_id;
    }
}

// 使用缓存系统的示例
$cache_system = new ContentLayoutCache();
$content_hash = md5($original_content);

if ($cached_content = $cache_system->get_cached_layout($content_hash, $template_id)) {
    echo $cached_content;
} else {
    $formatted_content = apply_content_template($original_content, $template_id);
    $cache_system->cache_layout($content_hash, $template_id, $formatted_content);
    echo $formatted_content;
}

5.2 移动端优化

确保智能排版在移动设备上的表现:

/* 移动端排版优化 */
@media (max-width: 768px) {
    .content-section {
        padding: 0 15px;
    }
    
    .intelligent-image {
        float: none !important;
        margin: 1em 0 !important;
        max-width: 100% !important;
    }
    
    h1, h2, h3 {
        line-height: 1.3;
        margin-top: 1.2em;
        margin-bottom: 0.6em;
    }
    
    p {
        font-size: calc(var(--content-font-size) * 0.9);
        line-height: 1.5;
    }
    
    /* 触摸友好的交互元素 */
    .interactive-element {
        min-height: 44px;
        min-width: 44px;
    }
}

六、未来发展趋势

6.1 AI驱动的个性化排版

未来的智能排版插件将集成机器学习算法,能够根据用户阅读习惯、设备类型和网络条件,实时调整排版策略。通过分析用户的滚动速度、停留时间和互动模式,系统可以优化字体大小、行间距和内容密度。

6.2 跨平台内容适配

随着内容在多平台分发的需求增加,智能排版插件将发展出更强大的跨平台适配能力,确保内容在网站、APP、社交媒体和邮件推送中都能保持一致的品牌形象和阅读体验。

结语

WordPress柔性内容智能排版插件代表了内容发布技术的未来方向。它不仅仅是一个工具,更是一种内容策略的体现。通过自动化处理繁琐的排版工作,内容创作者可以更专注于内容质量本身,而读者则能获得更优的阅读体验。随着技术的不断进步,智能排版将成为网络传媒机构的标准配置,推动整个行业向更高效、更专业的方向发展。

对于希望提升内容发布效率和质量的组织来说,投资并深入应用智能排版插件,不仅是技术升级,更是内容战略的重要布局。从基础配置到高级定制,从性能优化到未来规划,全面掌握这一工具,将在激烈的媒体竞争中占据重要优势。

七、插件集成与API开发

7.1 与第三方服务的API集成

/**
 * 智能排版插件API扩展
 * 提供REST API接口供外部系统调用
 */
class Flexible_Content_API {
    
    public function register_routes() {
        register_rest_route('flexible-content/v1', '/templates', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_available_templates'),
            'permission_callback' => array($this, 'check_api_permission')
        ));
        
        register_rest_route('flexible-content/v1', '/format', array(
            'methods' => 'POST',
            'callback' => array($this, 'format_content'),
            'permission_callback' => array($this, 'check_api_permission')
        ));
        
        register_rest_route('flexible-content/v1', '/batch-process', array(
            'methods' => 'POST',
            'callback' => array($this, 'batch_process_content'),
            'permission_callback' => array($this, 'check_api_permission')
        ));
    }
    
    /**
     * 获取可用模板列表
     */
    public function get_available_templates($request) {
        $templates = get_option('flexible_content_templates', array());
        
        // 过滤只返回公开模板
        $public_templates = array_filter($templates, function($template) {
            return isset($template['public']) && $template['public'] === true;
        });
        
        return rest_ensure_response(array(
            'success' => true,
            'data' => array_values($public_templates),
            'count' => count($public_templates)
        ));
    }
    
    /**
     * 格式化内容API
     */
    public function format_content($request) {
        $parameters = $request->get_json_params();
        
        // 验证必要参数
        if (empty($parameters['content']) || empty($parameters['template_id'])) {
            return new WP_Error('missing_parameters', '缺少必要参数', array('status' => 400));
        }
        
        $content = sanitize_text_field($parameters['content']);
        $template_id = sanitize_text_field($parameters['template_id']);
        $options = isset($parameters['options']) ? $parameters['options'] : array();
        
        // 应用模板
        $formatted_content = apply_content_template($content, $template_id);
        
        // 应用额外选项
        if (!empty($options['optimize_images'])) {
            $formatted_content = $this->optimize_content_images($formatted_content);
        }
        
        if (!empty($options['generate_toc']) && strlen($content) > 1500) {
            $formatted_content = $this->add_table_of_contents($formatted_content);
        }
        
        return rest_ensure_response(array(
            'success' => true,
            'data' => array(
                'formatted_content' => $formatted_content,
                'content_length' => strlen($formatted_content),
                'estimated_reading_time' => $this->calculate_reading_time($formatted_content)
            )
        ));
    }
    
    /**
     * 批量处理内容
     */
    public function batch_process_content($request) {
        $parameters = $request->get_json_params();
        $contents = $parameters['contents'] ?? array();
        $template_id = $parameters['template_id'] ?? 'default';
        
        if (empty($contents) || !is_array($contents)) {
            return new WP_Error('invalid_contents', '内容数据无效', array('status' => 400));
        }
        
        $results = array();
        $processed_count = 0;
        
        foreach ($contents as $index => $content_item) {
            if (!isset($content_item['id']) || !isset($content_item['content'])) {
                continue;
            }
            
            $formatted = apply_content_template(
                $content_item['content'], 
                $template_id
            );
            
            $results[] = array(
                'id' => $content_item['id'],
                'original_length' => strlen($content_item['content']),
                'formatted_length' => strlen($formatted),
                'formatted_content' => $formatted,
                'status' => 'success'
            );
            
            $processed_count++;
            
            // 防止超时,批量处理时每处理10条休息一下
            if ($processed_count % 10 === 0) {
                sleep(1);
            }
        }
        
        return rest_ensure_response(array(
            'success' => true,
            'processed' => $processed_count,
            'failed' => count($contents) - $processed_count,
            'results' => $results
        ));
    }
    
    /**
     * 权限检查
     */
    public function check_api_permission($request) {
        // 检查API密钥或用户权限
        $api_key = $request->get_header('X-API-Key');
        
        if ($api_key) {
            $valid_keys = get_option('flexible_content_api_keys', array());
            return in_array($api_key, $valid_keys);
        }
        
        // 或者检查WordPress用户权限
        return current_user_can('edit_posts');
    }
}

// 初始化API
add_action('rest_api_init', function() {
    $api = new Flexible_Content_API();
    $api->register_routes();
});

7.2 与编辑器的深度集成

/**
 * Gutenberg块编辑器集成
 * 创建自定义排版块
 */
class Flexible_Content_Gutenberg_Blocks {
    
    public function __construct() {
        add_action('enqueue_block_editor_assets', array($this, 'enqueue_editor_assets'));
        add_action('init', array($this, 'register_blocks'));
    }
    
    /**
     * 注册自定义Gutenberg块
     */
    public function register_blocks() {
        register_block_type('flexible-content/smart-layout', array(
            'editor_script' => 'flexible-content-blocks',
            'render_callback' => array($this, 'render_smart_layout_block'),
            'attributes' => array(
                'templateId' => array(
                    'type' => 'string',
                    'default' => 'default'
                ),
                'content' => array(
                    'type' => 'string',
                    'default' => ''
                ),
                'autoFormat' => array(
                    'type' => 'boolean',
                    'default' => true
                )
            )
        ));
        
        register_block_type('flexible-content/responsive-media', array(
            'editor_script' => 'flexible-content-blocks',
            'render_callback' => array($this, 'render_responsive_media_block'),
            'attributes' => array(
                'mediaType' => array(
                    'type' => 'string',
                    'default' => 'image'
                ),
                'mediaUrl' => array(
                    'type' => 'string',
                    'default' => ''
                ),
                'caption' => array(
                    'type' => 'string',
                    'default' => ''
                ),
                'alignment' => array(
                    'type' => 'string',
                    'default' => 'center'
                )
            )
        ));
    }
    
    /**
     * 渲染智能布局块
     */
    public function render_smart_layout_block($attributes) {
        $template_id = $attributes['templateId'] ?? 'default';
        $content = $attributes['content'] ?? '';
        $auto_format = $attributes['autoFormat'] ?? true;
        
        if (empty($content)) {
            return '<div class="flexible-content-empty">请添加内容</div>';
        }
        
        if ($auto_format) {
            $formatted_content = apply_content_template($content, $template_id);
        } else {
            $formatted_content = $content;
        }
        
        return sprintf(
            '<div class="flexible-content-block smart-layout" data-template="%s">%s</div>',
            esc_attr($template_id),
            $formatted_content
        );
    }
    
    /**
     * 加载编辑器资源
     */
    public function enqueue_editor_assets() {
        wp_enqueue_script(
            'flexible-content-blocks',
            plugins_url('blocks/dist/blocks.build.js', __FILE__),
            array('wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor'),
            '1.0.0',
            true
        );
        
        wp_localize_script('flexible-content-blocks', 'flexibleContentConfig', array(
            'templates' => get_option('flexible_content_templates', array()),
            'api_endpoint' => rest_url('flexible-content/v1/'),
            'nonce' => wp_create_nonce('wp_rest')
        ));
        
        wp_enqueue_style(
            'flexible-content-editor-styles',
            plugins_url('blocks/dist/blocks.editor.build.css', __FILE__),
            array('wp-edit-blocks')
        );
    }
}

// 初始化Gutenberg块
new Flexible_Content_Gutenberg_Blocks();

八、数据分析与智能优化

8.1 用户阅读行为分析

/**
 * 阅读行为追踪与分析系统
 * 收集用户与排版内容的互动数据
 */
class Reading_Behavior_Analytics {
    
    private $table_name;
    
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'reading_analytics';
        
        add_action('wp_footer', array($this, 'add_tracking_script'));
        add_action('wp_ajax_log_reading_behavior', array($this, 'log_reading_behavior'));
        add_action('wp_ajax_nopriv_log_reading_behavior', array($this, 'log_reading_behavior'));
    }
    
    /**
     * 创建分析数据表
     */
    public function create_analytics_table() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            user_id bigint(20) DEFAULT NULL,
            session_id varchar(64) NOT NULL,
            template_used varchar(50) NOT NULL,
            scroll_depth int(3) DEFAULT 0,
            reading_time int(11) DEFAULT 0,
            completion_rate float DEFAULT 0,
            device_type varchar(20) DEFAULT 'desktop',
            screen_width int(5) DEFAULT 0,
            screen_height int(5) DEFAULT 0,
            interactions json DEFAULT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY template_used (template_used),
            KEY created_at (created_at)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * 添加前端追踪脚本
     */
    public function add_tracking_script() {
        if (!is_single()) return;
        
        $current_post_id = get_the_ID();
        $template_used = get_post_meta($current_post_id, '_flexible_template', true);
        
        ?>
        <script type="text/javascript">
        (function() {
            'use strict';
            
            var readingData = {
                postId: <?php echo $current_post_id; ?>,
                templateUsed: '<?php echo esc_js($template_used); ?>',
                startTime: Date.now(),
                maxScroll: 0,
                interactions: [],
                lastScrollPosition: 0
            };
            
            // 追踪滚动深度
            function trackScrollDepth() {
                var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                var scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
                var scrollPercentage = scrollHeight > 0 ? Math.round((scrollTop / scrollHeight) * 100) : 0;
                
                if (scrollPercentage > readingData.maxScroll) {
                    readingData.maxScroll = scrollPercentage;
                }
            }
            
            // 追踪互动事件
            function trackInteractions(event) {
                var target = event.target;
                var interaction = {
                    type: event.type,
                    tag: target.tagName.toLowerCase(),
                    className: target.className || '',
                    timestamp: Date.now() - readingData.startTime
                };
                
                // 只记录有意义的互动
                if (['click', 'mouseover', 'focus'].includes(event.type)) {
                    readingData.interactions.push(interaction);
                }
            }
            
            // 发送数据到服务器
            function sendReadingData() {
                var readingTime = Math.round((Date.now() - readingData.startTime) / 1000);
                var completionRate = readingData.maxScroll >= 90 ? 1 : readingData.maxScroll / 100;
                
                var data = {
                    action: 'log_reading_behavior',
                    post_id: readingData.postId,
                    template_used: readingData.templateUsed,
                    scroll_depth: readingData.maxScroll,
                    reading_time: readingTime,
                    completion_rate: completionRate,
                    device_type: /Mobile|Android|iPhone/i.test(navigator.userAgent) ? 'mobile' : 'desktop',
                    screen_width: window.screen.width,
                    screen_height: window.screen.height,
                    interactions: JSON.stringify(readingData.interactions.slice(0, 50)) // 限制数据量
                };
                
                // 使用navigator.sendBeacon或XMLHttpRequest发送数据
                if (navigator.sendBeacon) {
                    var formData = new FormData();
                    Object.keys(data).forEach(function(key) {
                        formData.append(key, data[key]);
                    });
                    navigator.sendBeacon('<?php echo admin_url("admin-ajax.php"); ?>', formData);
                } else {
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '<?php echo admin_url("admin-ajax.php"); ?>', true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.send(new URLSearchParams(data).toString());
                }
            }
            
            // 事件监听
            window.addEventListener('scroll', trackScrollDepth, { passive: true });
            document.addEventListener('click', trackInteractions);
            document.addEventListener('mouseover', trackInteractions, { passive: true });
            
            // 页面卸载时发送数据
            window.addEventListener('beforeunload', sendReadingData);
            window.addEventListener('pagehide', sendReadingData);
            
            // 定期发送数据(每30秒)
            setInterval(sendReadingData, 30000);
            
        })();
        </script>
        <?php
    }
    
    /**
     * 记录阅读行为数据
     */
    public function log_reading_behavior() {
        // 验证nonce
        if (!check_ajax_referer('reading_tracking_nonce', 'security', false)) {
            wp_die('Invalid nonce', 403);
        }
        
        global $wpdb;
        
        $data = array(
            'post_id' => intval($_POST['post_id']),
            'user_id' => is_user_logged_in() ? get_current_user_id() : null,
            'session_id' => $this->get_session_id(),
            'template_used' => sanitize_text_field($_POST['template_used']),
            'scroll_depth' => min(100, max(0, intval($_POST['scroll_depth']))),
            'reading_time' => intval($_POST['reading_time']),
            'completion_rate' => floatval($_POST['completion_rate']),
            'device_type' => sanitize_text_field($_POST['device_type']),
            'screen_width' => intval($_POST['screen_width']),
            'screen_height' => intval($_POST['screen_height']),
            'interactions' => wp_json_encode(json_decode(stripslashes($_POST['interactions']), true))
        );
        
        $wpdb->insert($this->table_name, $data);
        
        wp_die('OK');
    }
    
    /**
     * 获取会话ID
     */
    private function get_session_id() {
        if (!isset($_COOKIE['reading_session'])) {
            $session_id = wp_generate_uuid4();
            setcookie('reading_session', $session_id, time() + 3600, '/');
            return $session_id;
        }
        return $_COOKIE['reading_session'];
    }
    
    /**
     * 获取排版效果分析报告
     */
    public function get_template_analytics($template_id, $days = 30) {
        global $wpdb;
        
        $start_date = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        $query = $wpdb->prepare(
            "SELECT 
                COUNT(*) as total_reads,
                AVG(scroll_depth) as avg_scroll_depth,
                AVG(reading_time) as avg_reading_time,
                AVG(completion_rate) as avg_completion_rate,
                device_type,
                DATE(created_at) as read_date
             FROM {$this->table_name}
             WHERE template_used = %s 
                AND created_at >= %s
             GROUP BY device_type, DATE(created_at)
             ORDER BY read_date DESC",
            $template_id,
            $start_date
        );
        
        $results = $wpdb->get_results($query, ARRAY_A);
        
        // 计算模板效果评分
        $effectiveness_score = $this->calculate_template_effectiveness($results);
        
        return array(
            'analytics' => $results,
            'effectiveness_score' => $effectiveness_score,
            'recommendations' => $this->generate_recommendations($results)
        );
    }
    
    /**
     * 计算模板效果评分
     */
    private function calculate_template_effectiveness($analytics_data) {
        if (empty($analytics_data)) {
            return 0;
        }
        
        $total_weight = 0;
        $weighted_score = 0;
        
        foreach ($analytics_data as $data) {
            // 滚动深度权重:40%
            $scroll_score = $data['avg_scroll_depth'] / 100;
            $weighted_score += $scroll_score * 0.4;
            $total_weight += 0.4;
            
            // 完成率权重:30%
            $completion_score = $data['avg_completion_rate'];
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/6201.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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