首页 / 应用软件 / 一步步教你,集成在线简易信息图表与数据报告生成工具到网站

一步步教你,集成在线简易信息图表与数据报告生成工具到网站

一步步教你,集成在线简易信息图表与数据报告生成工具到网站,通过WordPress程序的代码二次开发实现常用互联网小工具功能

引言:为什么你的网站需要信息图表与数据报告生成工具?

在当今数据驱动的互联网时代,可视化数据呈现已成为网站吸引用户、提升专业形象的关键手段。信息图表(Infographics)能够将复杂数据转化为直观、易懂的视觉形式,而数据报告生成工具则允许用户根据自身需求创建个性化内容。对于企业网站、博客、教育平台或任何需要展示数据的在线平台而言,集成这些功能可以显著提升用户体验和网站价值。

WordPress作为全球最流行的内容管理系统,拥有强大的扩展性和灵活性。通过代码二次开发,我们可以在WordPress网站上集成在线简易信息图表与数据报告生成工具,实现专业级的数据可视化功能,而无需依赖昂贵的外部服务或复杂的第三方插件。

本文将详细介绍如何通过WordPress代码二次开发,一步步实现这些功能,让你的网站具备创建和展示信息图表、生成数据报告的能力。

第一部分:准备工作与环境搭建

1.1 理解WordPress开发基础

在开始之前,我们需要了解WordPress开发的基本概念:

  • 主题与插件结构:WordPress功能扩展主要通过主题和插件实现
  • 钩子(Hooks)系统:动作钩子(Action Hooks)和过滤器钩子(Filter Hooks)是WordPress扩展的核心机制
  • 短代码(Shortcodes):允许在文章和页面中嵌入动态内容
  • 自定义文章类型(Custom Post Types):用于创建特殊类型的内容
  • REST API:WordPress提供的API接口,用于前后端数据交互

1.2 开发环境配置

为了安全地进行代码开发,建议搭建本地开发环境:

  1. 本地服务器环境:使用XAMPP、MAMP或Local by Flywheel等工具
  2. 代码编辑器:推荐VS Code、PHPStorm或Sublime Text
  3. 版本控制:安装Git用于代码版本管理
  4. 浏览器开发者工具:熟悉Chrome或Firefox的开发者工具

1.3 创建开发用子主题或插件

为了避免直接修改主题文件导致更新时丢失更改,我们创建一个专用插件:

<?php
/**
 * Plugin Name: 简易信息图表与数据报告生成工具
 * Plugin URI: https://yourwebsite.com/
 * Description: 为WordPress网站添加在线信息图表和数据报告生成功能
 * Version: 1.0.0
 * Author: 你的名字
 * License: GPL v2 or later
 */

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

// 定义插件常量
define('INFOGRAPHIC_TOOL_VERSION', '1.0.0');
define('INFOGRAPHIC_TOOL_PATH', plugin_dir_path(__FILE__));
define('INFOGRAPHIC_TOOL_URL', plugin_dir_url(__FILE__));

第二部分:创建信息图表生成器核心功能

2.1 设计数据库结构

我们需要存储用户创建的信息图表模板和数据。在插件激活时创建必要的数据库表:

// 激活插件时创建数据库表
register_activation_hook(__FILE__, 'infographic_tool_create_tables');

function infographic_tool_create_tables() {
    global $wpdb;
    
    $charset_collate = $wpdb->get_charset_collate();
    $table_name = $wpdb->prefix . 'infographic_templates';
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        title varchar(255) NOT NULL,
        template_data longtext NOT NULL,
        template_type varchar(50) DEFAULT 'chart',
        created_by bigint(20) NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 创建图表数据表
    $data_table = $wpdb->prefix . 'infographic_charts';
    
    $sql2 = "CREATE TABLE IF NOT EXISTS $data_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        template_id mediumint(9) NOT NULL,
        chart_data longtext NOT NULL,
        chart_options longtext NOT NULL,
        user_id bigint(20),
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        FOREIGN KEY (template_id) REFERENCES {$table_name}(id) ON DELETE CASCADE
    ) $charset_collate;";
    
    dbDelta($sql2);
}

2.2 创建信息图表编辑器界面

使用HTML、CSS和JavaScript创建前端编辑器:

// 添加信息图表编辑器短代码
add_shortcode('infographic_editor', 'infographic_tool_editor_shortcode');

function infographic_tool_editor_shortcode($atts) {
    // 只有登录用户可以使用编辑器
    if (!is_user_logged_in()) {
        return '<p>请先登录以使用信息图表编辑器。</p>';
    }
    
    // 加载必要资源
    wp_enqueue_style('infographic-editor-style', INFOGRAPHIC_TOOL_URL . 'assets/css/editor.css');
    wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', array(), '3.7.0', true);
    wp_enqueue_script('infographic-editor-script', INFOGRAPHIC_TOOL_URL . 'assets/js/editor.js', array('jquery', 'chart-js'), INFOGRAPHIC_TOOL_VERSION, true);
    
    // 传递数据到JavaScript
    wp_localize_script('infographic-editor-script', 'infographicTool', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('infographic_tool_nonce'),
        'user_id' => get_current_user_id()
    ));
    
    ob_start();
    ?>
    <div class="infographic-editor-container">
        <div class="editor-header">
            <h2>信息图表编辑器</h2>
            <div class="editor-actions">
                <button id="save-template" class="button button-primary">保存模板</button>
                <button id="load-template" class="button">加载模板</button>
                <button id="export-chart" class="button">导出图表</button>
            </div>
        </div>
        
        <div class="editor-main">
            <div class="sidebar">
                <div class="sidebar-section">
                    <h3>图表类型</h3>
                    <select id="chart-type" class="chart-type-select">
                        <option value="bar">柱状图</option>
                        <option value="line">折线图</option>
                        <option value="pie">饼图</option>
                        <option value="doughnut">环形图</option>
                        <option value="radar">雷达图</option>
                    </select>
                </div>
                
                <div class="sidebar-section">
                    <h3>数据输入</h3>
                    <div class="data-input">
                        <textarea id="chart-data" rows="10" placeholder="输入数据,格式:标签1,值1
标签2,值2
...">第一季度,120
第二季度,200
第三季度,150
第四季度,180</textarea>
                        <button id="update-chart" class="button">更新图表</button>
                    </div>
                </div>
                
                <div class="sidebar-section">
                    <h3>图表选项</h3>
                    <div class="chart-options">
                        <label>标题: <input type="text" id="chart-title" value="年度销售数据"></label>
                        <label>背景颜色: <input type="color" id="bg-color" value="#ffffff"></label>
                        <label>显示图例: <input type="checkbox" id="show-legend" checked></label>
                    </div>
                </div>
            </div>
            
            <div class="chart-container">
                <div class="chart-wrapper">
                    <canvas id="infographic-chart" width="800" height="500"></canvas>
                </div>
                <div class="chart-actions">
                    <button id="download-png" class="button">下载PNG</button>
                    <button id="download-pdf" class="button">下载PDF</button>
                    <button id="embed-code" class="button">获取嵌入代码</button>
                </div>
            </div>
        </div>
        
        <div class="templates-modal" id="templates-modal">
            <div class="modal-content">
                <span class="close-modal">&times;</span>
                <h3>选择模板</h3>
                <div class="templates-list" id="templates-list">
                    <!-- 模板将通过AJAX加载 -->
                </div>
            </div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

2.3 实现图表生成与保存功能

创建JavaScript文件处理图表生成和用户交互:

// assets/js/editor.js
jQuery(document).ready(function($) {
    let currentChart = null;
    let chartData = {
        labels: ['第一季度', '第二季度', '第三季度', '第四季度'],
        datasets: [{
            label: '销售额',
            data: [120, 200, 150, 180],
            backgroundColor: [
                'rgba(255, 99, 132, 0.6)',
                'rgba(54, 162, 235, 0.6)',
                'rgba(255, 206, 86, 0.6)',
                'rgba(75, 192, 192, 0.6)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 1
        }]
    };
    
    // 初始化图表
    function initChart() {
        const ctx = document.getElementById('infographic-chart').getContext('2d');
        const chartType = $('#chart-type').val();
        
        if (currentChart) {
            currentChart.destroy();
        }
        
        currentChart = new Chart(ctx, {
            type: chartType,
            data: chartData,
            options: {
                responsive: false,
                plugins: {
                    legend: {
                        display: $('#show-legend').is(':checked'),
                        position: 'top'
                    },
                    title: {
                        display: true,
                        text: $('#chart-title').val()
                    }
                }
            }
        });
    }
    
    // 更新图表数据
    $('#update-chart').on('click', function() {
        const dataText = $('#chart-data').val();
        const lines = dataText.split('n');
        const labels = [];
        const data = [];
        
        lines.forEach(line => {
            if (line.trim()) {
                const parts = line.split(',');
                if (parts.length >= 2) {
                    labels.push(parts[0].trim());
                    data.push(parseFloat(parts[1].trim()) || 0);
                }
            }
        });
        
        chartData.labels = labels;
        chartData.datasets[0].data = data;
        chartData.datasets[0].label = $('#chart-title').val() || '数据';
        
        initChart();
    });
    
    // 更改图表类型
    $('#chart-type').on('change', initChart);
    
    // 保存模板
    $('#save-template').on('click', function() {
        const templateName = prompt('请输入模板名称:');
        if (!templateName) return;
        
        const templateData = {
            chartType: $('#chart-type').val(),
            chartData: chartData,
            options: {
                title: $('#chart-title').val(),
                showLegend: $('#show-legend').is(':checked'),
                bgColor: $('#bg-color').val()
            }
        };
        
        $.ajax({
            url: infographicTool.ajax_url,
            type: 'POST',
            data: {
                action: 'save_infographic_template',
                nonce: infographicTool.nonce,
                title: templateName,
                data: JSON.stringify(templateData),
                user_id: infographicTool.user_id
            },
            success: function(response) {
                if (response.success) {
                    alert('模板保存成功!');
                } else {
                    alert('保存失败: ' + response.data);
                }
            }
        });
    });
    
    // 加载模板
    $('#load-template').on('click', function() {
        $.ajax({
            url: infographicTool.ajax_url,
            type: 'POST',
            data: {
                action: 'get_infographic_templates',
                nonce: infographicTool.nonce,
                user_id: infographicTool.user_id
            },
            success: function(response) {
                if (response.success) {
                    $('#templates-list').html('');
                    response.data.forEach(template => {
                        $('#templates-list').append(
                            `<div class="template-item" data-id="${template.id}">
                                <h4>${template.title}</h4>
                                <button class="load-template-btn button">加载</button>
                                <button class="delete-template-btn button">删除</button>
                            </div>`
                        );
                    });
                    $('#templates-modal').show();
                }
            }
        });
    });
    
    // 初始化图表
    initChart();
});

第三部分:实现数据报告生成功能

3.1 设计报告生成系统架构

数据报告生成器需要更复杂的结构,包括:

  1. 报告模板系统:预定义报告结构和样式
  2. 数据源连接:支持数据库、API或手动输入数据
  3. 报告生成引擎:将数据填充到模板中生成报告
  4. 导出功能:支持PDF、Word、Excel等格式

3.2 创建报告生成器短代码

// 添加报告生成器短代码
add_shortcode('report_generator', 'report_generator_shortcode');

function report_generator_shortcode($atts) {
    $atts = shortcode_atts(array(
        'type' => 'simple',
        'template' => 'default'
    ), $atts);
    
    // 加载资源
    wp_enqueue_style('report-generator-style', INFOGRAPHIC_TOOL_URL . 'assets/css/report-generator.css');
    wp_enqueue_script('report-generator-script', INFOGRAPHIC_TOOL_URL . 'assets/js/report-generator.js', array('jquery'), INFOGRAPHIC_TOOL_VERSION, true);
    wp_enqueue_script('html2pdf', 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js', array(), '0.10.1', true);
    
    ob_start();
    ?>
    <div class="report-generator-container">
        <div class="report-header">
            <h2>数据报告生成器</h2>
            <div class="report-actions">
                <select id="report-template">
                    <option value="business">业务报告</option>
                    <option value="financial">财务报告</option>
                    <option value="marketing">营销报告</option>
                    <option value="custom">自定义报告</option>
                </select>
                <button id="generate-report" class="button button-primary">生成报告</button>
                <button id="export-pdf" class="button">导出PDF</button>
            </div>
        </div>
        
        <div class="report-builder">
            <div class="data-sources">
                <h3>数据源</h3>
                <div class="source-options">
                    <label><input type="radio" name="data-source" value="manual" checked> 手动输入</label>
                    <label><input type="radio" name="data-source" value="csv"> 上传CSV</label>
                    <label><input type="radio" name="data-source" value="api"> API连接</label>
                </div>
                
                <div class="source-input manual-input">
                    <h4>输入报告数据</h4>
                    <div class="data-table-editor">
                        <table id="data-table">
                            <thead>
                                <tr>
                                    <th>指标</th>
                                    <th>Q1</th>
                                    <th>Q2</th>
                                    <th>Q3</th>
                                    <th>Q4</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input type="text" value="销售额" class="metric-name"></td>
                                    <td><input type="number" value="120000"></td>
                                    <td><input type="number" value="150000"></td>
                                    <td><input type="number" value="180000"></td>
                                    <td><input type="number" value="210000"></td>
                                </tr>
                                <!-- 更多行可以通过JavaScript添加 -->
                            </tbody>
                        </table>
                        <button id="add-row" class="button">添加行</button>
                    </div>
                </div>
            </div>
            
            <div class="report-preview">
                <h3>报告预览</h3>
                <div class="preview-container" id="report-preview">
                    <!-- 报告预览将通过JavaScript生成 -->
                </div>
            </div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

3.3 实现报告生成逻辑

创建PHP处理类来处理报告生成:

// 创建报告生成类
class Report_Generator {
    
    private $data;
    private $template;
    private $output_format;
    
    public function __construct($data, $template = 'default', $format = 'html') {
        $this->data = $data;
        $this->template = $template;
        $this->output_format = $format;
    }
    
    public function generate() {
        // 根据模板类型选择生成方法
        switch ($this->template) {
            case 'business':
                return $this->generate_business_report();
            case 'financial':
                return $this->generate_financial_report();
            case 'marketing':
                return $this->generate_marketing_report();
        default:
            return $this->generate_custom_report();
    }
}

private function generate_business_report() {
    $html = '<div class="business-report">';
    $html .= '<h1 class="report-title">业务分析报告</h1>';
    $html .= '<div class="report-meta">';
    $html .= '<p>生成日期: ' . date('Y年m月d日') . '</p>';
    $html .= '<p>报告周期: ' . ($this->data['period'] ?? '最近季度') . '</p>';
    $html .= '</div>';
    
    // 关键指标摘要
    if (!empty($this->data['metrics'])) {
        $html .= '<div class="key-metrics">';
        $html .= '<h2>关键绩效指标</h2>';
        $html .= '<div class="metrics-grid">';
        
        foreach ($this->data['metrics'] as $metric) {
            $html .= '<div class="metric-card">';
            $html .= '<h3>' . esc_html($metric['name']) . '</h3>';
            $html .= '<div class="metric-value">' . esc_html($metric['value']) . '</div>';
            if (isset($metric['change'])) {
                $change_class = $metric['change'] >= 0 ? 'positive' : 'negative';
                $html .= '<div class="metric-change ' . $change_class . '">';
                $html .= ($metric['change'] >= 0 ? '+' : '') . esc_html($metric['change']) . '%';
                $html .= '</div>';
            }
            $html .= '</div>';
        }
        
        $html .= '</div></div>';
    }
    
    // 数据表格
    if (!empty($this->data['table_data'])) {
        $html .= '<div class="data-table-section">';
        $html .= '<h2>详细数据</h2>';
        $html .= '<table class="report-table">';
        $html .= '<thead><tr>';
        
        // 表头
        foreach ($this->data['table_data']['headers'] as $header) {
            $html .= '<th>' . esc_html($header) . '</th>';
        }
        $html .= '</tr></thead><tbody>';
        
        // 表格内容
        foreach ($this->data['table_data']['rows'] as $row) {
            $html .= '<tr>';
            foreach ($row as $cell) {
                $html .= '<td>' . esc_html($cell) . '</td>';
            }
            $html .= '</tr>';
        }
        
        $html .= '</tbody></table></div>';
    }
    
    // 分析与建议
    $html .= '<div class="analysis-section">';
    $html .= '<h2>分析与建议</h2>';
    $html .= '<div class="analysis-content">';
    $html .= '<p>' . ($this->data['analysis'] ?? '基于以上数据,建议关注关键指标的变化趋势,优化资源配置。') . '</p>';
    $html .= '</div>';
    $html .= '</div>';
    
    $html .= '</div>';
    
    return $this->format_output($html);
}

private function format_output($html) {
    if ($this->output_format === 'pdf') {
        // 这里可以集成PDF生成库,如TCPDF或mPDF
        return $this->generate_pdf($html);
    }
    
    return $html;
}

private function generate_pdf($html) {
    // 简化示例,实际应使用PDF生成库
    return array(
        'type' => 'pdf',
        'content' => 'PDF生成功能需要集成第三方库',
        'html_template' => $html
    );
}

}

// AJAX处理报告生成
add_action('wp_ajax_generate_data_report', 'handle_report_generation');
add_action('wp_ajax_nopriv_generate_data_report', 'handle_report_generation');

function handle_report_generation() {

// 验证nonce
if (!wp_verify_nonce($_POST['nonce'], 'infographic_tool_nonce')) {
    wp_die('安全验证失败');
}

$data = json_decode(stripslashes($_POST['data']), true);
$template = sanitize_text_field($_POST['template']);
$format = sanitize_text_field($_POST['format'] ?? 'html');

$generator = new Report_Generator($data, $template, $format);
$report = $generator->generate();

wp_send_json_success(array(
    'report' => $report,
    'download_url' => $format === 'pdf' ? generate_pdf_download_link($report) : null
));

}


## 第四部分:创建管理界面与高级功能

### 4.1 构建WordPress管理界面

// 添加管理菜单
add_action('admin_menu', 'infographic_tool_admin_menu');

function infographic_tool_admin_menu() {

add_menu_page(
    '信息图表工具',
    '图表工具',
    'manage_options',
    'infographic-tool',
    'infographic_tool_admin_page',
    'dashicons-chart-area',
    30
);

add_submenu_page(
    'infographic-tool',
    '图表模板',
    '模板管理',
    'manage_options',
    'infographic-templates',
    'infographic_templates_page'
);

add_submenu_page(
    'infographic-tool',
    '报告设置',
    '报告设置',
    'manage_options',
    'infographic-reports',
    'infographic_reports_page'
);

add_submenu_page(
    'infographic-tool',
    '数据源配置',
    '数据源',
    'manage_options',
    'infographic-data-sources',
    'infographic_data_sources_page'
);

}

function infographic_tool_admin_page() {

?>
<div class="wrap">
    <h1>信息图表与数据报告工具</h1>
    
    <div class="dashboard-cards">
        <div class="card">
            <h3>使用统计</h3>
            <div class="card-content">
                <?php
                global $wpdb;
                $templates_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}infographic_templates");
                $charts_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}infographic_charts");
                ?>
                <p>模板数量: <strong><?php echo $templates_count; ?></strong></p>
                <p>生成图表: <strong><?php echo $charts_count; ?></strong></p>
            </div>
        </div>
        
        <div class="card">
            <h3>快速操作</h3>
            <div class="card-content">
                <p>
                    <a href="<?php echo admin_url('admin.php?page=infographic-templates'); ?>" class="button">管理模板</a>
                    <a href="<?php echo admin_url('admin.php?page=infographic-reports'); ?>" class="button">报告设置</a>
                </p>
                <p>短代码示例:</p>
                <code>[infographic_editor]</code><br>
                <code>[report_generator]</code>
            </div>
        </div>
    </div>
    
    <div class="settings-section">
        <h2>全局设置</h2>
        <form method="post" action="options.php">
            <?php
            settings_fields('infographic_tool_settings');
            do_settings_sections('infographic_tool_settings');
            ?>
            <table class="form-table">
                <tr>
                    <th>默认图表尺寸</th>
                    <td>
                        <input type="number" name="default_chart_width" value="<?php echo get_option('default_chart_width', 800); ?>" placeholder="宽度"> ×
                        <input type="number" name="default_chart_height" value="<?php echo get_option('default_chart_height', 500); ?>" placeholder="高度"> 像素
                    </td>
                </tr>
                <tr>
                    <th>允许的用户角色</th>
                    <td>
                        <?php
                        $roles = get_editable_roles();
                        $allowed_roles = get_option('infographic_allowed_roles', array('administrator', 'editor'));
                        foreach ($roles as $role_name => $role_info) {
                            $checked = in_array($role_name, $allowed_roles) ? 'checked' : '';
                            echo '<label style="display: block; margin-bottom: 5px;">';
                            echo '<input type="checkbox" name="allowed_roles[]" value="' . $role_name . '" ' . $checked . '> ';
                            echo $role_info['name'];
                            echo '</label>';
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <th>启用数据导出</th>
                    <td>
                        <label>
                            <input type="checkbox" name="enable_data_export" value="1" <?php checked(get_option('enable_data_export', 1)); ?>>
                            允许用户导出图表数据
                        </label>
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
</div>
<?php

}

// 注册设置
add_action('admin_init', 'infographic_tool_register_settings');

function infographic_tool_register_settings() {

register_setting('infographic_tool_settings', 'default_chart_width');
register_setting('infographic_tool_settings', 'default_chart_height');
register_setting('infographic_tool_settings', 'infographic_allowed_roles');
register_setting('infographic_tool_settings', 'enable_data_export');

}


### 4.2 实现模板管理系统

function infographic_templates_page() {

global $wpdb;

// 处理模板操作
if (isset($_GET['action'])) {
    if ($_GET['action'] === 'delete' && isset($_GET['template_id'])) {
        $template_id = intval($_GET['template_id']);
        $wpdb->delete(
            $wpdb->prefix . 'infographic_templates',
            array('id' => $template_id)
        );
        echo '<div class="notice notice-success"><p>模板已删除</p></div>';
    }
}

// 获取所有模板
$templates = $wpdb->get_results("
    SELECT t.*, u.user_login as author 
    FROM {$wpdb->prefix}infographic_templates t
    LEFT JOIN {$wpdb->users} u ON t.created_by = u.ID
    ORDER BY t.created_at DESC
");
?>
<div class="wrap">
    <h1>图表模板管理</h1>
    
    <div class="tablenav top">
        <div class="alignleft actions">
            <a href="<?php echo admin_url('admin.php?page=infographic-tool&action=add_template'); ?>" class="button button-primary">添加新模板</a>
        </div>
    </div>
    
    <table class="wp-list-table widefat fixed striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>模板名称</th>
                <th>类型</th>
                <th>作者</th>
                <th>创建时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($templates)): ?>
                <tr>
                    <td colspan="6" style="text-align: center;">暂无模板</td>
                </tr>
            <?php else: ?>
                <?php foreach ($templates as $template): ?>
                    <tr>
                        <td><?php echo $template->id; ?></td>
                        <td><?php echo esc_html($template->title); ?></td>
                        <td><?php echo esc_html($template->template_type); ?></td>
                        <td><?php echo esc_html($template->author); ?></td>
                        <td><?php echo date('Y-m-d H:i', strtotime($template->created_at)); ?></td>
                        <td>
                            <a href="<?php echo admin_url("admin.php?page=infographic-tool&action=edit_template&id={$template->id}"); ?>" class="button button-small">编辑</a>
                            <a href="<?php echo admin_url("admin.php?page=infographic-templates&action=delete&template_id={$template->id}"); ?>" class="button button-small button-link-delete" onclick="return confirm('确定删除此模板?')">删除</a>
                            <button class="button button-small preview-template" data-id="<?php echo $template->id; ?>">预览</button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- 模板预览模态框 -->
<div id="template-preview-modal" class="modal" style="display:none;">
    <div class="modal-content">
        <span class="close-modal">&times;</span>
        <div id="template-preview-content"></div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    $('.preview-template').on('click', function() {
        var templateId = $(this).data('id');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'preview_infographic_template',
                template_id: templateId,
                nonce: '<?php echo wp_create_nonce('infographic_preview_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $('#template-preview-content').html(response.data.preview);
                    $('#template-preview-modal').show();
                }
            }
        });
    });
    
    $('.close-modal').on('click', function() {
        $('#template-preview-modal').hide();
    });
});
</script>
<?php

}


### 4.3 添加REST API端点

// 注册REST API端点
add_action('rest_api_init', 'register_infographic_rest_routes');

function register_infographic_rest_routes() {

// 获取图表数据
register_rest_route('infographic-tool/v1', '/charts/(?P<id>d+)', array(
    'methods' => 'GET',
    'callback' => 'get_chart_data_api',
    'permission_callback' => function() {
        return current_user_can('read');
    }
));

// 创建新图表
register_rest_route('infographic-tool/v1', '/charts', array(
    'methods' => 'POST',
    'callback' => 'create_chart_api',
    'permission_callback' => function() {
        return current_user_can('edit_posts');
    }
));

// 获取报告模板
register_rest_route('infographic-tool/v1', '/report-templates', array(
    'methods' => 'GET',
    'callback' => 'get_report_templates_api',
    'permission_callback' => function() {
        return current_user_can('read');
    }
));

}

function get_chart_data_api($request) {

$chart_id = $request['id'];

global $wpdb;
$chart = $wpdb->get_row($wpdb->prepare(
    "SELECT * FROM {$wpdb->prefix}infographic_charts WHERE id = %d",
    $chart_id
));

if (!$chart) {
    return new WP_Error('not_found', '图表未找到', array('status' => 404));
}

return array(
    'id' => $chart->id,
    'data' => json_decode($chart->chart_data),
    'options' => json_decode($chart->chart_options),
    'created_at' => $chart->created_at
);

}

function create_chart_api($request) {

$parameters = $request->get_json_params();

if (empty($parameters['data']) || empty($parameters['template_id'])) {
    return new WP_Error('invalid_data', '缺少必要数据', array('status' => 400));
}

global $wpdb;

$result = $wpdb->insert(
    $wpdb->prefix . 'infographic_charts',
    array(
        'template_id' => intval($parameters['template_id']),
        'chart_data' => json_encode($parameters['data']),
        'chart_options' => json_encode($parameters['options'] ?? array()),
        'user_id' => get_current_user_id()
    ),
    array('%d', '%s', '%s', '%d')
);

if ($result === false) {
    return new WP_Error('db_error', '数据库错误', array('status' => 500));
}

return array(
    'id' => $wpdb->insert_id,
    'message' => '图表创建成功',
    'embed_code' => generate_chart_embed_code($wpdb->insert_id)
);

}

function generate_chart_embed_code($chart_id) {

$embed_url = home_url("/infographic-embed/{$chart_id}/");
return '<iframe src="' . esc_url($embed_url) . '" width="800" height="500" frameborder="0"></iframe>';

}


## 第五部分:优化与安全增强

### 5.1 数据安全与验证

// 增强数据验证
class Data_Validator {


public static function validate_chart_data($data) {
    $errors = array();
    
    // 验证数据格式
    if (!is_array($data)) {
        $errors[] = '数据格式不正确';
        return $errors;
    }
    
    // 验证标签
    if (empty($data['labels']) || !is_array($data['labels'])) {
        $errors[] = '标签数据不能为空';
    }
    
    // 验证数据集
    if (empty($data['datasets']) || !is_array($data['datasets'])) {
        $errors[] = '数据集不能为空';
    } else {
        foreach ($data['datasets'] as $index => $dataset) {
            if (empty($dataset['data']) || !is_array($dataset['data'])) {
                $errors[] = "数据集 {$index} 的数据不能为空";
            }
            
            // 验证数据值是否为数字
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5369.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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