首页 / 教程文章 / WordPress小批量定制插件实现工艺文件管理的教程

WordPress小批量定制插件实现工艺文件管理的教程

WordPress小批量定制插件实现工艺文件管理教程

一、前言:为什么需要工艺文件管理插件

在制造业、手工艺品行业或设计工作室中,工艺文件管理是一个至关重要的环节。传统的文件管理方式存在诸多不便:文件分散存储、版本混乱、权限管理困难等。通过WordPress定制插件,我们可以为中小企业提供一个经济高效的解决方案。

本教程将指导您开发一个适用于小批量生产的工艺文件管理插件,实现文件上传、分类、版本控制和权限管理等功能。我们将采用模块化开发方式,确保代码的可维护性和扩展性。

二、环境准备与插件基础结构

2.1 创建插件基本文件

首先,在WordPress的wp-content/plugins/目录下创建新文件夹craft-file-manager,并创建以下基础文件:

<?php
/**
 * Plugin Name: 工艺文件管理器
 * Plugin URI:  https://yourwebsite.com/craft-file-manager
 * Description: 用于管理小批量生产中的工艺文件,支持版本控制和权限管理
 * Version:     1.0.0
 * Author:      您的名称
 * License:     GPL v2 or later
 * Text Domain: craft-file-manager
 */

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

// 定义插件常量
define('CFM_VERSION', '1.0.0');
define('CFM_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CFM_PLUGIN_URL', plugin_dir_url(__FILE__));

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

function cfm_init_plugin() {
    // 检查必要依赖
    if (!class_exists('WP_List_Table')) {
        require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
    }
    
    // 加载核心类
    require_once CFM_PLUGIN_DIR . 'includes/class-craft-file-manager.php';
    require_once CFM_PLUGIN_DIR . 'includes/class-file-handler.php';
    require_once CFM_PLUGIN_DIR . 'includes/class-permission-manager.php';
    
    // 初始化主类
    $craft_file_manager = Craft_File_Manager::get_instance();
}

2.2 创建数据库表

工艺文件管理需要存储文件信息、版本记录等数据。在插件激活时创建必要的数据库表:

<?php
// 文件:includes/class-install.php

class CFM_Installer {
    
    public static function activate() {
        self::create_tables();
        self::create_default_roles();
    }
    
    private static function create_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        $table_prefix = $wpdb->prefix . 'cfm_';
        
        // 工艺文件表
        $files_table = $table_prefix . 'files';
        $sql_files = "CREATE TABLE IF NOT EXISTS $files_table (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            file_name varchar(255) NOT NULL,
            file_path varchar(500) NOT NULL,
            file_type varchar(50) NOT NULL,
            file_size bigint(20) NOT NULL,
            project_id mediumint(9) DEFAULT 0,
            category_id mediumint(9) DEFAULT 0,
            version varchar(20) DEFAULT '1.0',
            description text,
            uploader_id bigint(20) NOT NULL,
            upload_date datetime DEFAULT CURRENT_TIMESTAMP,
            is_latest tinyint(1) DEFAULT 1,
            download_count mediumint(9) DEFAULT 0,
            PRIMARY KEY (id),
            KEY project_id (project_id),
            KEY category_id (category_id)
        ) $charset_collate;";
        
        // 文件版本历史表
        $versions_table = $table_prefix . 'file_versions';
        $sql_versions = "CREATE TABLE IF NOT EXISTS $versions_table (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            file_id mediumint(9) NOT NULL,
            version varchar(20) NOT NULL,
            file_path varchar(500) NOT NULL,
            change_log text,
            updated_by bigint(20) NOT NULL,
            updated_date datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY file_id (file_id)
        ) $charset_collate;";
        
        // 文件权限表
        $permissions_table = $table_prefix . 'file_permissions';
        $sql_permissions = "CREATE TABLE IF NOT EXISTS $permissions_table (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            file_id mediumint(9) NOT NULL,
            user_id bigint(20) DEFAULT NULL,
            role_id bigint(20) DEFAULT NULL,
            can_view tinyint(1) DEFAULT 0,
            can_edit tinyint(1) DEFAULT 0,
            can_delete tinyint(1) DEFAULT 0,
            can_download tinyint(1) DEFAULT 0,
            PRIMARY KEY (id),
            KEY file_id (file_id),
            KEY user_id (user_id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql_files);
        dbDelta($sql_versions);
        dbDelta($sql_permissions);
    }
    
    private static function create_default_roles() {
        // 添加工艺文件管理相关角色能力
        $roles = ['administrator', 'editor'];
        
        foreach ($roles as $role_name) {
            $role = get_role($role_name);
            if ($role) {
                $role->add_cap('cfm_upload_files');
                $role->add_cap('cfm_manage_files');
                $role->add_cap('cfm_view_all_files');
            }
        }
        
        // 为作者添加基本权限
        $author_role = get_role('author');
        if ($author_role) {
            $author_role->add_cap('cfm_upload_files');
            $author_role->add_cap('cfm_view_own_files');
        }
    }
}

// 注册激活和卸载钩子
register_activation_hook(__FILE__, ['CFM_Installer', 'activate']);
register_uninstall_hook(__FILE__, ['CFM_Installer', 'uninstall']);

三、核心功能实现

3.1 文件上传与处理类

<?php
// 文件:includes/class-file-handler.php

class CFM_File_Handler {
    
    private $allowed_types = [
        'pdf'  => 'application/pdf',
        'doc'  => 'application/msword',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'xls'  => 'application/vnd.ms-excel',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'jpg'  => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'png'  => 'image/png',
        'dwg'  => 'application/acad',
        'dxf'  => 'application/dxf'
    ];
    
    private $max_file_size = 10485760; // 10MB
    
    public function upload_file($file, $project_id = 0, $category_id = 0, $description = '') {
        // 检查用户权限
        if (!current_user_can('cfm_upload_files')) {
            return new WP_Error('no_permission', '您没有上传文件的权限');
        }
        
        // 验证文件
        $validation = $this->validate_file($file);
        if (is_wp_error($validation)) {
            return $validation;
        }
        
        // 创建上传目录
        $upload_dir = $this->create_upload_directory();
        if (is_wp_error($upload_dir)) {
            return $upload_dir;
        }
        
        // 生成唯一文件名
        $file_name = $this->generate_unique_filename($file['name'], $upload_dir);
        $file_path = $upload_dir . '/' . $file_name;
        
        // 移动上传的文件
        if (!move_uploaded_file($file['tmp_name'], $file_path)) {
            return new WP_Error('upload_failed', '文件上传失败');
        }
        
        // 保存到数据库
        $file_id = $this->save_file_to_db([
            'file_name'    => $file['name'],
            'file_path'    => $file_path,
            'file_type'    => $file['type'],
            'file_size'    => $file['size'],
            'project_id'   => $project_id,
            'category_id'  => $category_id,
            'description'  => $description,
            'uploader_id'  => get_current_user_id(),
            'version'      => '1.0'
        ]);
        
        if (!$file_id) {
            // 删除已上传的文件
            unlink($file_path);
            return new WP_Error('db_error', '文件信息保存失败');
        }
        
        // 设置默认权限
        $this->set_default_permissions($file_id);
        
        return [
            'success' => true,
            'file_id' => $file_id,
            'file_path' => $file_path,
            'message' => '文件上传成功'
        ];
    }
    
    private function validate_file($file) {
        // 检查文件是否上传成功
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return new WP_Error('upload_error', '文件上传过程中出现错误');
        }
        
        // 检查文件大小
        if ($file['size'] > $this->max_file_size) {
            return new WP_Error('file_too_large', '文件大小不能超过10MB');
        }
        
        // 检查文件类型
        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!array_key_exists($file_ext, $this->allowed_types)) {
            return new WP_Error('invalid_type', '不支持的文件类型');
        }
        
        // 验证MIME类型
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
        
        if ($mime_type !== $this->allowed_types[$file_ext]) {
            return new WP_Error('mime_mismatch', '文件MIME类型不匹配');
        }
        
        return true;
    }
    
    private function create_upload_directory() {
        $upload_dir = wp_upload_dir();
        $cfm_dir = $upload_dir['basedir'] . '/craft-files';
        
        // 按年份和月份创建子目录
        $year_month = date('Y/m');
        $full_path = $cfm_dir . '/' . $year_month;
        
        if (!file_exists($full_path)) {
            if (!wp_mkdir_p($full_path)) {
                return new WP_Error('dir_creation_failed', '无法创建上传目录');
            }
            
            // 创建保护文件
            $this->create_protection_files($full_path);
        }
        
        return $full_path;
    }
    
    private function create_protection_files($directory) {
        // 创建.htaccess文件防止直接访问
        $htaccess_content = "Options -IndexesnDeny from all";
        file_put_contents($directory . '/.htaccess', $htaccess_content);
        
        // 创建index.html空白文件
        file_put_contents($directory . '/index.html', '');
    }
    
    private function generate_unique_filename($original_name, $directory) {
        $extension = pathinfo($original_name, PATHINFO_EXTENSION);
        $base_name = pathinfo($original_name, PATHINFO_FILENAME);
        
        // 清理文件名
        $clean_name = sanitize_file_name($base_name);
        $filename = $clean_name . '.' . $extension;
        
        $counter = 1;
        while (file_exists($directory . '/' . $filename)) {
            $filename = $clean_name . '-' . $counter . '.' . $extension;
            $counter++;
        }
        
        return $filename;
    }
    
    private function save_file_to_db($file_data) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_files';
        
        $result = $wpdb->insert(
            $table_name,
            $file_data,
            ['%s', '%s', '%s', '%d', '%d', '%d', '%s', '%d', '%s', '%d']
        );
        
        return $result ? $wpdb->insert_id : false;
    }
    
    private function set_default_permissions($file_id) {
        $uploader_id = get_current_user_id();
        
        // 上传者拥有所有权限
        $this->add_permission($file_id, $uploader_id, null, 1, 1, 1, 1);
        
        // 管理员和编辑者默认有查看权限
        $admin_users = get_users(['role__in' => ['administrator', 'editor']]);
        
        foreach ($admin_users as $user) {
            if ($user->ID != $uploader_id) {
                $this->add_permission($file_id, $user->ID, null, 1, 0, 0, 1);
            }
        }
    }
    
    private function add_permission($file_id, $user_id, $role_id, $can_view, $can_edit, $can_delete, $can_download) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_file_permissions';
        
        return $wpdb->insert(
            $table_name,
            [
                'file_id' => $file_id,
                'user_id' => $user_id,
                'role_id' => $role_id,
                'can_view' => $can_view,
                'can_edit' => $can_edit,
                'can_delete' => $can_delete,
                'can_download' => $can_download
            ],
            ['%d', '%d', '%d', '%d', '%d', '%d', '%d']
        );
    }
}

3.2 文件版本管理

<?php
// 文件:includes/class-version-manager.php

class CFM_Version_Manager {
    
    public function create_new_version($file_id, $new_file, $change_log = '') {
        global $wpdb;
        
        // 获取当前文件信息
        $current_file = $this->get_file_by_id($file_id);
        if (!$current_file) {
            return new WP_Error('file_not_found', '文件不存在');
        }
        
        // 检查编辑权限
        if (!$this->can_edit_file($file_id, get_current_user_id())) {
            return new WP_Error('no_edit_permission', '您没有编辑此文件的权限');
        }
        
        // 处理新版本文件上传
        $file_handler = new CFM_File_Handler();
        $upload_result = $file_handler->upload_file($new_file);
        
        if (is_wp_error($upload_result)) {
            return $upload_result;
        }
        
        // 计算新版本号
        $new_version = $this->calculate_next_version($current_file->version);
        
        // 保存版本历史
        $this->save_version_history($file_id, $current_file->version, $current_file->file_path, $change_log);
        
        // 更新主文件记录
        $this->update_file_version($file_id, $new_version, $upload_result['file_path']);
        
        return [
            'success' => true,
            'new_version' => $new_version,
            'file_id' => $file_id,
            'message' => '新版本创建成功'
        ];
    }
    
    private function calculate_next_version($current_version) {
        // 简单版本号递增逻辑,可根据需要扩展
        $parts = explode('.', $current_version);
        
        if (count($parts) == 1) {
            return (int)$parts[0] + 1 . '.0';
        } else {
            $major = (int)$parts[0];
            $minor = (int)$parts[1];
            return $major . '.' . ($minor + 1);
        }
    }
    
    private function save_version_history($file_id, $version, $file_path, $change_log) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_file_versions';
        
        return $wpdb->insert(
            $table_name,
            [
                'file_id' => $file_id,
                'version' => $version,
                'file_path' => $file_path,
                'change_log' => $change_log,
                'updated_by' => get_current_user_id()
            ],
            ['%d', '%s', '%s', '%s', '%d']
        );
    }
    
    private function update_file_version($file_id, $new_version, $new_file_path) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_files';
        
        // 将当前版本标记为非最新
        $wpdb->update(
            $table_name,
            ['is_latest' => 0],
            ['id' => $file_id],
            ['%d'],
            ['%d']
        );
        
        // 创建新记录作为最新版本
        $current_file = $this->get_file_by_id($file_id);
        
        $new_file_data = [
            'file_name' => basename($new_file_path),
            'file_path' => $new_file_path,
            'file_type' => mime_content_type($new_file_path),
            'file_size' => filesize($new_file_path),
            'project_id' => $current_file->project_id,
            'category_id' => $current_file->category_id,
            'version' => $new_version,
            'description' => $current_file->description,
            'uploader_id' => get_current_user_id(),
            'is_latest' => 1
        ];
        
        return $wpdb->insert(
            $table_name,
            $new_file_data,
            ['%s', '%s', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%d']
        );
    }
    

3.3 权限管理系统

<?php
// 文件:includes/class-permission-manager.php

class CFM_Permission_Manager {
    
    /**
     * 检查用户对文件的权限
     * @param int $file_id 文件ID
     * @param int $user_id 用户ID
     * @param string $action 操作类型:view, edit, delete, download
     * @return bool 是否有权限
     */
    public function check_permission($file_id, $user_id, $action) {
        // 管理员拥有所有权限
        if (user_can($user_id, 'cfm_manage_files')) {
            return true;
        }
        
        // 获取用户角色
        $user = get_userdata($user_id);
        $user_roles = $user->roles;
        
        // 检查用户特定权限
        $user_permission = $this->get_user_permission($file_id, $user_id);
        if ($user_permission && $this->check_action_permission($user_permission, $action)) {
            return true;
        }
        
        // 检查角色权限
        foreach ($user_roles as $role) {
            $role_permission = $this->get_role_permission($file_id, $role);
            if ($role_permission && $this->check_action_permission($role_permission, $action)) {
                return true;
            }
        }
        
        // 检查是否为文件上传者
        if ($this->is_file_uploader($file_id, $user_id)) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 获取用户特定权限
     */
    private function get_user_permission($file_id, $user_id) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_file_permissions';
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name 
             WHERE file_id = %d AND user_id = %d",
            $file_id, $user_id
        ));
    }
    
    /**
     * 获取角色权限
     */
    private function get_role_permission($file_id, $role_name) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_file_permissions';
        $role = get_role($role_name);
        
        if (!$role) {
            return null;
        }
        
        // 获取角色ID(这里使用角色名称的哈希值作为标识)
        $role_id = crc32($role_name);
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name 
             WHERE file_id = %d AND role_id = %d",
            $file_id, $role_id
        ));
    }
    
    /**
     * 检查具体操作权限
     */
    private function check_action_permission($permission, $action) {
        $permission_map = [
            'view' => 'can_view',
            'edit' => 'can_edit',
            'delete' => 'can_delete',
            'download' => 'can_download'
        ];
        
        if (!isset($permission_map[$action])) {
            return false;
        }
        
        $column = $permission_map[$action];
        return isset($permission->$column) && $permission->$column == 1;
    }
    
    /**
     * 检查是否为文件上传者
     */
    private function is_file_uploader($file_id, $user_id) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_files';
        
        $result = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name 
             WHERE id = %d AND uploader_id = %d",
            $file_id, $user_id
        ));
        
        return $result > 0;
    }
    
    /**
     * 设置文件权限
     */
    public function set_permissions($file_id, $permissions_data) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_file_permissions';
        
        // 删除现有权限
        $wpdb->delete($table_name, ['file_id' => $file_id], ['%d']);
        
        // 添加新权限
        foreach ($permissions_data as $permission) {
            $wpdb->insert(
                $table_name,
                [
                    'file_id' => $file_id,
                    'user_id' => isset($permission['user_id']) ? $permission['user_id'] : null,
                    'role_id' => isset($permission['role_id']) ? $permission['role_id'] : null,
                    'can_view' => $permission['can_view'] ? 1 : 0,
                    'can_edit' => $permission['can_edit'] ? 1 : 0,
                    'can_delete' => $permission['can_delete'] ? 1 : 0,
                    'can_download' => $permission['can_download'] ? 1 : 0
                ],
                ['%d', '%d', '%d', '%d', '%d', '%d', '%d']
            );
        }
        
        return true;
    }
    
    /**
     * 获取文件的所有权限设置
     */
    public function get_file_permissions($file_id) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_file_permissions';
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table_name WHERE file_id = %d",
            $file_id
        ));
    }
}

四、后台管理界面

4.1 文件列表管理页面

<?php
// 文件:admin/class-file-list-table.php

class CFM_File_List_Table extends WP_List_Table {
    
    public function __construct() {
        parent::__construct([
            'singular' => '工艺文件',
            'plural'   => '工艺文件',
            'ajax'     => false
        ]);
    }
    
    public function get_columns() {
        return [
            'cb'           => '<input type="checkbox" />',
            'file_name'    => '文件名',
            'file_type'    => '类型',
            'file_size'    => '大小',
            'version'      => '版本',
            'project'      => '项目',
            'category'     => '分类',
            'uploader'     => '上传者',
            'upload_date'  => '上传时间',
            'downloads'    => '下载次数',
            'actions'      => '操作'
        ];
    }
    
    public function column_default($item, $column_name) {
        return isset($item[$column_name]) ? $item[$column_name] : '—';
    }
    
    public function column_file_name($item) {
        $actions = [];
        
        // 根据权限显示操作按钮
        $permission_manager = new CFM_Permission_Manager();
        $user_id = get_current_user_id();
        
        if ($permission_manager->check_permission($item['id'], $user_id, 'view')) {
            $actions['view'] = sprintf(
                '<a href="?page=cfm-view-file&file_id=%d">查看</a>',
                $item['id']
            );
        }
        
        if ($permission_manager->check_permission($item['id'], $user_id, 'download')) {
            $actions['download'] = sprintf(
                '<a href="%s" target="_blank">下载</a>',
                wp_nonce_url(
                    admin_url('admin-ajax.php?action=cfm_download_file&file_id=' . $item['id']),
                    'cfm_download_' . $item['id']
                )
            );
        }
        
        if ($permission_manager->check_permission($item['id'], $user_id, 'edit')) {
            $actions['edit'] = sprintf(
                '<a href="?page=cfm-edit-file&file_id=%d">编辑</a>',
                $item['id']
            );
        }
        
        if ($permission_manager->check_permission($item['id'], $user_id, 'delete')) {
            $actions['delete'] = sprintf(
                '<a href="%s" onclick="return confirm('确定要删除吗?')">删除</a>',
                wp_nonce_url(
                    admin_url('admin.php?page=cfm-files&action=delete&file_id=' . $item['id']),
                    'cfm_delete_file_' . $item['id']
                )
            );
        }
        
        return sprintf(
            '<strong>%1$s</strong>%2$s',
            $item['file_name'],
            $this->row_actions($actions)
        );
    }
    
    public function column_file_size($item) {
        return size_format($item['file_size'], 2);
    }
    
    public function column_actions($item) {
        $permission_manager = new CFM_Permission_Manager();
        $user_id = get_current_user_id();
        
        $buttons = '';
        
        if ($permission_manager->check_permission($item['id'], $user_id, 'edit')) {
            $buttons .= sprintf(
                '<button class="button button-small" onclick="location.href='?page=cfm-new-version&file_id=%d'">新版本</button> ',
                $item['id']
            );
        }
        
        if ($permission_manager->check_permission($item['id'], $user_id, 'edit')) {
            $buttons .= sprintf(
                '<button class="button button-small" onclick="location.href='?page=cfm-manage-permissions&file_id=%d'">权限</button>',
                $item['id']
            );
        }
        
        return $buttons;
    }
    
    public function get_bulk_actions() {
        $actions = [];
        
        if (current_user_can('cfm_manage_files')) {
            $actions['bulk_download'] = '批量下载';
            $actions['bulk_delete'] = '批量删除';
        }
        
        return $actions;
    }
    
    public function prepare_items() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'cfm_files';
        $per_page = 20;
        $current_page = $this->get_pagenum();
        $offset = ($current_page - 1) * $per_page;
        
        // 构建查询条件
        $where = "WHERE is_latest = 1";
        $user_id = get_current_user_id();
        
        // 如果不是管理员,只显示有权限的文件
        if (!current_user_can('cfm_view_all_files')) {
            $permission_manager = new CFM_Permission_Manager();
            // 这里简化处理,实际应用中需要更复杂的权限查询
            $where .= " AND (uploader_id = $user_id OR EXISTS (
                SELECT 1 FROM {$wpdb->prefix}cfm_file_permissions 
                WHERE file_id = {$table_name}.id AND user_id = $user_id AND can_view = 1
            ))";
        }
        
        // 处理搜索
        if (!empty($_REQUEST['s'])) {
            $search = sanitize_text_field($_REQUEST['s']);
            $where .= $wpdb->prepare(" AND (file_name LIKE %s OR description LIKE %s)", 
                '%' . $wpdb->esc_like($search) . '%',
                '%' . $wpdb->esc_like($search) . '%'
            );
        }
        
        // 处理分类筛选
        if (!empty($_REQUEST['category_id'])) {
            $category_id = intval($_REQUEST['category_id']);
            $where .= $wpdb->prepare(" AND category_id = %d", $category_id);
        }
        
        // 获取总数
        $total_items = $wpdb->get_var("SELECT COUNT(*) FROM $table_name $where");
        
        // 获取数据
        $this->items = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table_name $where 
             ORDER BY upload_date DESC 
             LIMIT %d OFFSET %d",
            $per_page, $offset
        ), ARRAY_A);
        
        // 设置分页参数
        $this->set_pagination_args([
            'total_items' => $total_items,
            'per_page'    => $per_page,
            'total_pages' => ceil($total_items / $per_page)
        ]);
    }
}

4.2 文件上传表单

<?php
// 文件:admin/partials/file-upload-form.php

function cfm_render_upload_form() {
    // 检查权限
    if (!current_user_can('cfm_upload_files')) {
        wp_die('您没有上传文件的权限');
    }
    
    // 获取项目和分类列表
    $projects = cfm_get_projects();
    $categories = cfm_get_categories();
    
    ?>
    <div class="wrap">
        <h1>上传工艺文件</h1>
        
        <form method="post" enctype="multipart/form-data" action="<?php echo admin_url('admin-post.php'); ?>">
            <input type="hidden" name="action" value="cfm_upload_file">
            <?php wp_nonce_field('cfm_upload_file_action', 'cfm_upload_nonce'); ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="cfm_file">选择文件</label></th>
                    <td>
                        <input type="file" name="cfm_file" id="cfm_file" required>
                        <p class="description">支持的文件类型:PDF, DOC, DOCX, XLS, XLSX, JPG, PNG, DWG, DXF</p>
                        <p class="description">最大文件大小:10MB</p>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row"><label for="cfm_project">关联项目</label></th>
                    <td>
                        <select name="cfm_project" id="cfm_project">
                            <option value="0">-- 选择项目 --</option>
                            <?php foreach ($projects as $project): ?>
                            <option value="<?php echo $project->id; ?>">
                                <?php echo esc_html($project->name); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row"><label for="cfm_category">文件分类</label></th>
                    <td>
                        <select name="cfm_category" id="cfm_category">
                            <option value="0">-- 选择分类 --</option>
                            <?php foreach ($categories as $category): ?>
                            <option value="<?php echo $category->id; ?>">
                                <?php echo esc_html($category->name); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row"><label for="cfm_description">文件描述</label></th>
                    <td>
                        <textarea name="cfm_description" id="cfm_description" 
                                  rows="4" cols="50" 
                                  placeholder="请输入文件描述信息..."></textarea>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row"><label>访问权限</label></th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text">默认权限设置</legend>
                            <label>
                                <input type="checkbox" name="cfm_permission_admin" value="1" checked>
                                管理员可查看
                            </label><br>
                            <label>
                                <input type="checkbox" name="cfm_permission_editor" value="1">
                                编辑者可查看
                            </label><br>
                            <label>
                                <input type="checkbox" name="cfm_permission_author" value="1">
                                作者可查看
                            </label>
                        </fieldset>
                        <p class="description">上传后可在文件权限管理中详细设置</p>
                    </td>
                </tr>
            </table>
            
            <p class="submit">
                <input type="submit" name="submit" id="submit" class="button button-primary" value="上传文件">
                <a href="<?php echo admin_url('admin.php?page=cfm-files'); ?>" class="button">返回列表</a>
            </p>
        </form>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        // 文件大小验证
        $('#cfm_file').on('change', function() {
            var file = this.files[0];
            if (file && file.size > 10 * 1024 * 1024) {
                alert('文件大小不能超过10MB');
                this.value = '';
            }
        });
        
        // 表单提交验证
        $('form').on('submit', function(e) {
            var fileInput = $('#cfm_file')[0];
            if (!fileInput.files.length) {
                alert('请选择要上传的文件');
                e.preventDefault();
                return false;
            }
        });
    });
    </script>
    <?php
}

五、前端展示与短代码

5.1 文件展示短代码

<?php
// 文件:includes/class-shortcodes.php

class CFM_Shortcodes {
    
    public static function init() {
        add_shortcode('craft_files', [__CLASS__, 'render_files_list']);
        add_shortcode('craft_file_download', [__CLASS__, 'render_download_button']);
        add_shortcode('craft_file_gallery', [__CLASS__, 'render_file_gallery']);
    }
    
    /**
     * 显示文件列表短代码
     * 用法:[craft_files category="1" project="2" limit="10"]
     */
    public static function render_files_list($atts) {
        $atts = shortcode_atts([
            'category' => 0,
            'project'  => 0,
            'limit'    => 10,
            'columns'  => 2
        ], $atts, 'craft_files');
        
        global $wpdb;
        $table_name = $wpdb->prefix . 'cfm_files';
        
        // 构建查询
        $where = ['is_latest = 1'];
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5994.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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