首页 / 教程文章 / 支持柔性生产的WordPress小批量定制插件教程

支持柔性生产的WordPress小批量定制插件教程

支持柔性生产的WordPress小批量定制插件教程

引言:柔性生产与WordPress的结合

在当今个性化消费时代,小批量定制生产已成为制造业的重要趋势。柔性生产系统能够快速响应客户需求,实现按需生产。对于使用WordPress搭建的电商网站而言,如何将这种柔性生产能力整合到在线销售平台中,是一个值得探索的课题。

本教程将指导您开发一个支持柔性生产的WordPress小批量定制插件,让客户能够在线定制产品并直接下单生产。我们将从需求分析开始,逐步实现完整的插件功能。

插件需求分析与设计

功能需求

  1. 产品定制界面:客户可在线选择产品参数
  2. 实时价格计算:根据定制选项自动计算价格
  3. 生产参数导出:将定制参数转换为生产指令
  4. 订单管理后台:商家可查看和管理定制订单
  5. 与WooCommerce集成:作为WooCommerce的扩展插件

数据库设计

我们需要创建以下数据表:

  • 定制产品模板表:存储可定制产品的参数定义
  • 用户定制记录表:存储每个订单的定制参数
  • 生产参数映射表:将定制参数转换为机器可读格式

插件基础结构搭建

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

flexible-production-customizer/
├── flexible-production-customizer.php    # 主插件文件
├── includes/
│   ├── class-database.php                # 数据库操作类
│   ├── class-product-customizer.php      # 产品定制类
│   ├── class-order-manager.php           # 订单管理类
│   └── class-admin-interface.php         # 后台管理类
├── assets/
│   ├── css/
│   │   └── customizer-frontend.css       # 前端样式
│   └── js/
│       └── customizer-frontend.js        # 前端交互脚本
├── templates/
│   ├── product-customizer.php            # 定制界面模板
│   └── admin-order-details.php           # 订单详情模板
└── languages/                            # 国际化文件

主插件文件代码

<?php
/**
 * Plugin Name: 柔性生产小批量定制插件
 * Plugin URI: https://yourwebsite.com/
 * Description: 支持柔性生产的小批量产品定制插件,可与WooCommerce集成
 * Version: 1.0.0
 * Author: 您的名称
 * License: GPL v2 or later
 * Text Domain: flexible-production-customizer
 */

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

// 定义插件常量
define('FPC_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('FPC_PLUGIN_URL', plugin_dir_url(__FILE__));
define('FPC_VERSION', '1.0.0');

// 检查WooCommerce是否激活
function fpc_check_woocommerce() {
    if (!class_exists('WooCommerce')) {
        add_action('admin_notices', function() {
            ?>
            <div class="notice notice-error">
                <p><?php _e('柔性生产定制插件需要WooCommerce支持,请先安装并激活WooCommerce插件。', 'flexible-production-customizer'); ?></p>
            </div>
            <?php
        });
        return false;
    }
    return true;
}

// 初始化插件
function fpc_init() {
    if (!fpc_check_woocommerce()) {
        return;
    }
    
    // 加载必要文件
    require_once FPC_PLUGIN_PATH . 'includes/class-database.php';
    require_once FPC_PLUGIN_PATH . 'includes/class-product-customizer.php';
    require_once FPC_PLUGIN_PATH . 'includes/class-order-manager.php';
    require_once FPC_PLUGIN_PATH . 'includes/class-admin-interface.php';
    
    // 初始化各个组件
    FPC_Database::init();
    FPC_Product_Customizer::init();
    FPC_Order_Manager::init();
    FPC_Admin_Interface::init();
    
    // 加载文本域
    load_plugin_textdomain('flexible-production-customizer', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
add_action('plugins_loaded', 'fpc_init');

// 激活插件时创建数据库表
register_activation_hook(__FILE__, ['FPC_Database', 'create_tables']);

// 停用插件时的清理操作
register_deactivation_hook(__FILE__, function() {
    // 可以在这里添加清理代码,但通常保留数据
    flush_rewrite_rules();
});

数据库操作类实现

<?php
/**
 * 数据库操作类
 * 处理插件的所有数据库操作
 */
class FPC_Database {
    
    /**
     * 初始化数据库类
     */
    public static function init() {
        // 注册自定义数据库表
        add_action('init', [__CLASS__, 'register_tables'], 0);
    }
    
    /**
     * 创建插件所需的数据库表
     */
    public static function create_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // 定制产品模板表
        $table_name = $wpdb->prefix . 'fpc_product_templates';
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            product_id bigint(20) NOT NULL,
            template_name varchar(200) NOT NULL,
            options longtext NOT NULL,
            price_rules longtext NOT NULL,
            production_mapping longtext NOT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY product_id (product_id)
        ) $charset_collate;";
        
        // 用户定制记录表
        $table_name2 = $wpdb->prefix . 'fpc_customizations';
        $sql2 = "CREATE TABLE IF NOT EXISTS $table_name2 (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            order_id bigint(20) NOT NULL,
            product_id bigint(20) NOT NULL,
            customization_data longtext NOT NULL,
            calculated_price decimal(10,2) NOT NULL,
            production_instructions longtext NOT NULL,
            status varchar(50) DEFAULT 'pending',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY order_id (order_id),
            KEY product_id (product_id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        dbDelta($sql2);
    }
    
    /**
     * 保存定制产品模板
     * 
     * @param int $product_id 产品ID
     * @param string $template_name 模板名称
     * @param array $options 定制选项
     * @param array $price_rules 价格规则
     * @param array $production_mapping 生产参数映射
     * @return int|false 插入的ID或false
     */
    public static function save_product_template($product_id, $template_name, $options, $price_rules, $production_mapping) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'fpc_product_templates';
        
        $result = $wpdb->insert(
            $table_name,
            [
                'product_id' => $product_id,
                'template_name' => $template_name,
                'options' => json_encode($options, JSON_UNESCAPED_UNICODE),
                'price_rules' => json_encode($price_rules, JSON_UNESCAPED_UNICODE),
                'production_mapping' => json_encode($production_mapping, JSON_UNESCAPED_UNICODE)
            ],
            ['%d', '%s', '%s', '%s', '%s']
        );
        
        return $result ? $wpdb->insert_id : false;
    }
    
    /**
     * 获取产品的定制模板
     * 
     * @param int $product_id 产品ID
     * @return array|false 模板数据或false
     */
    public static function get_product_template($product_id) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'fpc_product_templates';
        
        $template = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM $table_name WHERE product_id = %d ORDER BY id DESC LIMIT 1",
                $product_id
            ),
            ARRAY_A
        );
        
        if ($template) {
            $template['options'] = json_decode($template['options'], true);
            $template['price_rules'] = json_decode($template['price_rules'], true);
            $template['production_mapping'] = json_decode($template['production_mapping'], true);
        }
        
        return $template;
    }
    
    /**
     * 保存用户定制记录
     * 
     * @param int $order_id 订单ID
     * @param int $product_id 产品ID
     * @param array $customization_data 定制数据
     * @param float $calculated_price 计算后的价格
     * @param array $production_instructions 生产指令
     * @return int|false 插入的ID或false
     */
    public static function save_customization($order_id, $product_id, $customization_data, $calculated_price, $production_instructions) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'fpc_customizations';
        
        $result = $wpdb->insert(
            $table_name,
            [
                'order_id' => $order_id,
                'product_id' => $product_id,
                'customization_data' => json_encode($customization_data, JSON_UNESCAPED_UNICODE),
                'calculated_price' => $calculated_price,
                'production_instructions' => json_encode($production_instructions, JSON_UNESCAPED_UNICODE)
            ],
            ['%d', '%d', '%s', '%f', '%s']
        );
        
        return $result ? $wpdb->insert_id : false;
    }
}

产品定制前端界面

前端JavaScript交互代码

/**
 * 产品定制前端交互脚本
 * 处理定制界面的动态交互和价格计算
 */
jQuery(document).ready(function($) {
    'use strict';
    
    // 产品定制器类
    class ProductCustomizer {
        constructor(productId, templateData) {
            this.productId = productId;
            this.template = templateData;
            this.customization = {};
            this.basePrice = parseFloat($('.fpc-base-price').data('base-price')) || 0;
            this.init();
        }
        
        // 初始化定制器
        init() {
            this.bindEvents();
            this.loadInitialOptions();
            this.updatePrice();
        }
        
        // 绑定事件
        bindEvents() {
            // 选项变更事件
            $(document).on('change', '.fpc-option', (e) => {
                this.handleOptionChange(e.target);
            });
            
            // 数量变更事件
            $(document).on('change', '.fpc-quantity', (e) => {
                this.handleQuantityChange(e.target);
            });
            
            // 添加到购物车
            $(document).on('click', '.fpc-add-to-cart', (e) => {
                e.preventDefault();
                this.addToCart();
            });
        }
        
        // 加载初始选项
        loadInitialOptions() {
            // 为每个选项设置默认值
            this.template.options.forEach(option => {
                const defaultValue = option.default || 
                                   (option.type === 'select' ? option.choices[0].value : 
                                    option.type === 'checkbox' ? false : '');
                
                this.customization[option.id] = defaultValue;
                
                // 设置DOM元素的默认值
                const $element = $(`[data-option-id="${option.id}"]`);
                if ($element.length) {
                    if (option.type === 'select') {
                        $element.val(defaultValue);
                    } else if (option.type === 'checkbox') {
                        $element.prop('checked', defaultValue);
                    } else {
                        $element.val(defaultValue);
                    }
                }
            });
        }
        
        // 处理选项变更
        handleOptionChange(element) {
            const $element = $(element);
            const optionId = $element.data('option-id');
            let value;
            
            // 根据输入类型获取值
            if ($element.attr('type') === 'checkbox') {
                value = $element.is(':checked');
            } else if ($element.attr('type') === 'radio') {
                if ($element.is(':checked')) {
                    value = $element.val();
                }
            } else {
                value = $element.val();
            }
            
            // 更新定制数据
            this.customization[optionId] = value;
            
            // 更新预览(如果存在)
            this.updatePreview(optionId, value);
            
            // 更新价格
            this.updatePrice();
        }
        
        // 处理数量变更
        handleQuantityChange(element) {
            const quantity = parseInt($(element).val()) || 1;
            this.customization.quantity = quantity;
            this.updatePrice();
        }
        
        // 更新价格
        updatePrice() {
            let totalPrice = this.basePrice;
            let breakdown = [];
            
            // 计算每个选项的价格
            this.template.options.forEach(option => {
                const value = this.customization[option.id];
                if (value !== undefined && value !== '' && value !== false) {
                    const priceRule = this.findPriceRule(option.id, value);
                    if (priceRule) {
                        totalPrice += parseFloat(priceRule.price) || 0;
                        breakdown.push({
                            name: option.name,
                            value: this.getOptionDisplayValue(option, value),
                            price: priceRule.price
                        });
                    }
                }
            });
            
            // 应用数量
            const quantity = this.customization.quantity || 1;
            totalPrice = totalPrice * quantity;
            
            // 更新显示
            this.updatePriceDisplay(totalPrice, breakdown);
        }
        
        // 查找价格规则
        findPriceRule(optionId, value) {
            if (!this.template.price_rules) return null;
            
            return this.template.price_rules.find(rule => 
                rule.option_id === optionId && rule.value === value.toString()
            );
        }
        
        // 获取选项显示值
        getOptionDisplayValue(option, value) {
            if (option.type === 'select') {
                const choice = option.choices.find(c => c.value === value);
                return choice ? choice.label : value;
            }
            return value;
        }
        
        // 更新价格显示
        updatePriceDisplay(totalPrice, breakdown) {
            // 更新总价
            $('.fpc-total-price').text(this.formatPrice(totalPrice));
            
            // 更新价格明细
            const $breakdown = $('.fpc-price-breakdown');
            if ($breakdown.length) {
                let html = '<ul>';
                breakdown.forEach(item => {
                    html += `<li>${item.name}: ${item.value} (+${this.formatPrice(item.price)})</li>`;
                });
                html += '</ul>';
                $breakdown.html(html);
            }
        }
        
        // 更新预览
        updatePreview(optionId, value) {
            // 这里可以添加预览更新逻辑
            // 例如:更新产品图片、显示文本预览等
            console.log(`选项 ${optionId} 更新为: ${value}`);
        }
        
        // 添加到购物车
        addToCart() {
            // 验证必填选项
            if (!this.validateOptions()) {
                alert('请完成所有必填选项');
                return;
            }
            
            // 准备数据
            const data = {
                action: 'fpc_add_to_cart',
                product_id: this.productId,
                customization: this.customization,
                quantity: this.customization.quantity || 1,
                nonce: fpc_ajax.nonce
            };
            
            // 显示加载状态
            $('.fpc-add-to-cart').prop('disabled', true).text('添加中...');
            
            // 发送AJAX请求
            $.post(fpc_ajax.ajax_url, data, (response) => {
                if (response.success) {
                    // 成功添加到购物车
                    alert('产品已添加到购物车!');
                    
                    // 可选:更新购物车图标数量
                    if (response.data.cart_count) {
                        $('.cart-count').text(response.data.cart_count);
                    }
                    
                    // 可选:重定向到购物车页面
                    if (fpc_ajax.redirect_to_cart) {
                        window.location.href = fpc_ajax.cart_url;
                    }
                } else {
                    alert('添加失败: ' + response.data.message);
                }
                
                // 恢复按钮状态
                $('.fpc-add-to-cart').prop('disabled', false).text('添加到购物车');
            }).fail(() => {
                alert('请求失败,请稍后重试');
                $('.fpc-add-to-cart').prop('disabled', false).text('添加到购物车');
            });
        }
        
        // 验证选项
        validateOptions() {
            let isValid = true;
            
            this.template.options.forEach(option => {
                if (option.required) {
                    const value = this.customization[option.id];
                    if (value === undefined || value === '' || value === false) {
                        isValid = false;
                        // 高亮显示必填选项
                        $(`[data-option-id="${option.id}"]`).addClass('fpc-required-error');
                    } else {
                        $(`[data-option-id="${option.id}"]`).removeClass('fpc-required-error');
                    }
                }
            });
            
            return isValid;
        }
        
        // 格式化价格
        formatPrice(price) {
            return fpc_ajax.currency_symbol + parseFloat(price).toFixed(2);
        }
    }
    
    // 初始化定制器(如果页面中有定制器容器)
    if ($('#fpc-product-customizer').length) {
        const productId = $('#fpc-product-customizer').data('product-id');
        const templateData = window.fpc_template_data;
        
        if (productId && templateData) {

window.fpcCustomizer = new ProductCustomizer(productId, templateData);

    }
}

});


## 产品定制器PHP类实现

<?php
/**

  • 产品定制器类
  • 处理前端定制逻辑和WooCommerce集成
    */

class FPC_Product_Customizer {


/**
 * 初始化产品定制器
 */
public static function init() {
    // 在产品页面添加定制器
    add_action('woocommerce_before_add_to_cart_button', [__CLASS__, 'display_customizer']);
    
    // 处理添加到购物车的定制产品
    add_filter('woocommerce_add_cart_item_data', [__CLASS__, 'add_customization_to_cart_item'], 10, 2);
    
    // 在购物车中显示定制信息
    add_filter('woocommerce_get_item_data', [__CLASS__, 'display_customization_in_cart'], 10, 2);
    
    // 保存定制信息到订单
    add_action('woocommerce_checkout_create_order_line_item', [__CLASS__, 'save_customization_to_order'], 10, 4);
    
    // 注册AJAX处理
    add_action('wp_ajax_fpc_add_to_cart', [__CLASS__, 'ajax_add_to_cart']);
    add_action('wp_ajax_nopriv_fpc_add_to_cart', [__CLASS__, 'ajax_add_to_cart']);
    
    // 注册短代码
    add_shortcode('fpc_customizer', [__CLASS__, 'customizer_shortcode']);
}

/**
 * 在产品页面显示定制器
 */
public static function display_customizer() {
    global $product;
    
    // 检查产品是否支持定制
    if (!self::is_product_customizable($product->get_id())) {
        return;
    }
    
    // 获取产品定制模板
    $template = FPC_Database::get_product_template($product->get_id());
    if (!$template) {
        return;
    }
    
    // 加载定制器模板
    include FPC_PLUGIN_PATH . 'templates/product-customizer.php';
    
    // 输出模板数据供JS使用
    self::output_template_data($template);
}

/**
 * 检查产品是否支持定制
 * 
 * @param int $product_id 产品ID
 * @return bool 是否支持定制
 */
public static function is_product_customizable($product_id) {
    // 这里可以添加更复杂的逻辑,比如检查产品分类、标签等
    $template = FPC_Database::get_product_template($product_id);
    return !empty($template);
}

/**
 * 输出模板数据到JavaScript
 * 
 * @param array $template 模板数据
 */
public static function output_template_data($template) {
    wp_localize_script('fpc-frontend', 'fpc_template_data', [
        'options' => $template['options'],
        'price_rules' => $template['price_rules'],
        'production_mapping' => $template['production_mapping']
    ]);
    
    wp_localize_script('fpc-frontend', 'fpc_ajax', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('fpc_customizer_nonce'),
        'currency_symbol' => get_woocommerce_currency_symbol(),
        'cart_url' => wc_get_cart_url(),
        'redirect_to_cart' => get_option('fpc_redirect_to_cart', false)
    ]);
}

/**
 * 将定制数据添加到购物车项目
 * 
 * @param array $cart_item_data 购物车项目数据
 * @param int $product_id 产品ID
 * @return array 修改后的购物车项目数据
 */
public static function add_customization_to_cart_item($cart_item_data, $product_id) {
    if (isset($_POST['fpc_customization'])) {
        $customization = json_decode(stripslashes($_POST['fpc_customization']), true);
        
        if ($customization) {
            // 计算定制价格
            $calculated_price = self::calculate_customization_price($product_id, $customization);
            
            // 保存定制数据
            $cart_item_data['fpc_customization'] = [
                'data' => $customization,
                'calculated_price' => $calculated_price
            ];
            
            // 设置定制产品的价格
            add_filter('woocommerce_add_cart_item', function($cart_item) use ($calculated_price) {
                if (isset($cart_item['fpc_customization'])) {
                    $cart_item['data']->set_price($calculated_price);
                }
                return $cart_item;
            });
        }
    }
    
    return $cart_item_data;
}

/**
 * 计算定制价格
 * 
 * @param int $product_id 产品ID
 * @param array $customization 定制数据
 * @return float 计算后的价格
 */
public static function calculate_customization_price($product_id, $customization) {
    $product = wc_get_product($product_id);
    $base_price = $product->get_price();
    
    $template = FPC_Database::get_product_template($product_id);
    if (!$template) {
        return $base_price;
    }
    
    $total_price = $base_price;
    
    // 应用价格规则
    foreach ($template['price_rules'] as $rule) {
        if (isset($customization[$rule['option_id']]) && 
            $customization[$rule['option_id']] == $rule['value']) {
            $total_price += floatval($rule['price']);
        }
    }
    
    // 应用数量
    $quantity = isset($customization['quantity']) ? intval($customization['quantity']) : 1;
    
    return $total_price * $quantity;
}

/**
 * 在购物车中显示定制信息
 * 
 * @param array $item_data 项目数据
 * @param array $cart_item 购物车项目
 * @return array 修改后的项目数据
 */
public static function display_customization_in_cart($item_data, $cart_item) {
    if (isset($cart_item['fpc_customization'])) {
        $customization = $cart_item['fpc_customization']['data'];
        $template = FPC_Database::get_product_template($cart_item['product_id']);
        
        if ($template) {
            foreach ($template['options'] as $option) {
                $option_id = $option['id'];
                if (isset($customization[$option_id]) && !empty($customization[$option_id])) {
                    $value = $customization[$option_id];
                    
                    // 获取显示值
                    $display_value = self::get_option_display_value($option, $value);
                    
                    $item_data[] = [
                        'name' => $option['name'],
                        'value' => $display_value
                    ];
                }
            }
            
            // 显示定制价格
            $item_data[] = [
                'name' => '定制价格',
                'value' => wc_price($cart_item['fpc_customization']['calculated_price'])
            ];
        }
    }
    
    return $item_data;
}

/**
 * 获取选项的显示值
 * 
 * @param array $option 选项配置
 * @param mixed $value 选项值
 * @return string 显示值
 */
public static function get_option_display_value($option, $value) {
    if ($option['type'] === 'select') {
        foreach ($option['choices'] as $choice) {
            if ($choice['value'] == $value) {
                return $choice['label'];
            }
        }
    } elseif ($option['type'] === 'checkbox') {
        return $value ? '是' : '否';
    }
    
    return $value;
}

/**
 * 保存定制信息到订单
 * 
 * @param WC_Order_Item_Product $item 订单项目
 * @param string $cart_item_key 购物车项目键
 * @param array $values 值数组
 * @param WC_Order $order 订单对象
 */
public static function save_customization_to_order($item, $cart_item_key, $values, $order) {
    if (isset($values['fpc_customization'])) {
        $customization = $values['fpc_customization']['data'];
        $calculated_price = $values['fpc_customization']['calculated_price'];
        
        // 保存到订单项目元数据
        $item->add_meta_data('_fpc_customization', $customization);
        $item->add_meta_data('_fpc_calculated_price', $calculated_price);
        
        // 生成生产指令
        $production_instructions = self::generate_production_instructions(
            $values['product_id'],
            $customization
        );
        
        // 保存到定制记录表
        FPC_Database::save_customization(
            $order->get_id(),
            $values['product_id'],
            $customization,
            $calculated_price,
            $production_instructions
        );
    }
}

/**
 * 生成生产指令
 * 
 * @param int $product_id 产品ID
 * @param array $customization 定制数据
 * @return array 生产指令
 */
public static function generate_production_instructions($product_id, $customization) {
    $template = FPC_Database::get_product_template($product_id);
    if (!$template || !isset($template['production_mapping'])) {
        return [];
    }
    
    $instructions = [];
    
    // 根据映射规则转换定制数据为生产指令
    foreach ($template['production_mapping'] as $mapping) {
        $option_id = $mapping['option_id'];
        $machine_param = $mapping['machine_parameter'];
        
        if (isset($customization[$option_id])) {
            $value = $customization[$option_id];
            
            // 应用值转换(如果有)
            if (isset($mapping['value_mapping'])) {
                $value_mapping = json_decode($mapping['value_mapping'], true);
                if (isset($value_mapping[$value])) {
                    $value = $value_mapping[$value];
                }
            }
            
            $instructions[] = [
                'machine' => $mapping['machine'],
                'parameter' => $machine_param,
                'value' => $value,
                'unit' => $mapping['unit'] ?? ''
            ];
        }
    }
    
    return $instructions;
}

/**
 * AJAX添加到购物车处理
 */
public static function ajax_add_to_cart() {
    // 验证nonce
    if (!check_ajax_referer('fpc_customizer_nonce', 'nonce', false)) {
        wp_die('安全验证失败', 403);
    }
    
    $product_id = intval($_POST['product_id']);
    $customization = json_decode(stripslashes($_POST['customization']), true);
    $quantity = intval($_POST['quantity']);
    
    if (!$product_id || !$customization) {
        wp_send_json_error(['message' => '无效的参数']);
    }
    
    // 添加到购物车
    $cart_item_key = WC()->cart->add_to_cart(
        $product_id,
        $quantity,
        0,
        [],
        ['fpc_customization' => [
            'data' => $customization,
            'calculated_price' => self::calculate_customization_price($product_id, $customization)
        ]]
    );
    
    if ($cart_item_key) {
        wp_send_json_success([
            'message' => '产品已添加到购物车',
            'cart_count' => WC()->cart->get_cart_contents_count(),
            'cart_url' => wc_get_cart_url()
        ]);
    } else {
        wp_send_json_error(['message' => '添加到购物车失败']);
    }
}

/**
 * 定制器短代码
 * 
 * @param array $atts 短代码属性
 * @return string 定制器HTML
 */
public static function customizer_shortcode($atts) {
    $atts = shortcode_atts([
        'product_id' => 0,
        'template_id' => 0
    ], $atts);
    
    ob_start();
    
    if ($atts['product_id']) {
        $product = wc_get_product($atts['product_id']);
        if ($product && self::is_product_customizable($atts['product_id'])) {
            $template = FPC_Database::get_product_template($atts['product_id']);
            include FPC_PLUGIN_PATH . 'templates/product-customizer.php';
            self::output_template_data($template);
        }
    }
    
    return ob_get_clean();
}

}


## 后台管理界面实现

<?php
/**

  • 后台管理界面类
  • 提供产品模板管理和订单查看功能
    */

class FPC_Admin_Interface {


/**
 * 初始化后台界面
 */
public static function init() {
    // 添加管理菜单
    add_action('admin_menu', [__CLASS__, 'add_admin_menu']);
    
    // 在产品编辑页面添加定制设置
    add_action('woocommerce_product_options_general_product_data', [__CLASS__, 'add_product_customizer_settings']);
    add_action('woocommerce_process_product_meta', [__CLASS__, 'save_product_customizer_settings']);
    
    // 在订单页面显示定制信息
    add_action('woocommerce_admin_order_item_values', [__CLASS__, 'display_order_item_customization'], 10, 3);
    
    // 添加生产指令导出功能
    add_action('add_meta_boxes', [__CLASS__, 'add_production_instructions_meta_box']);
    
    // 注册管理脚本和样式
    add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_admin_assets']);
}

/**
 * 添加管理菜单
 */
public static function add_admin_menu() {
    add_submenu_page(
        'woocommerce',
        '柔性生产定制',
        '柔性生产定制',
        'manage_woocommerce',
        'fpc-settings',
        [__CLASS__, 'render_settings_page']
    );
    
    add_submenu_page(
        'woocommerce',
        '定制订单管理',
        '定制订单',
        'manage_woocommerce',
        'fpc-orders',
        [__CLASS__, 'render_orders_page']
    );
}

/**
 * 渲染设置页面
 */
public static function render_settings_page() {
    ?>
    <div class="wrap">
        <h1>柔性生产定制插件设置</h1>
        
        <form method="post" action="options.php">
            <?php
            settings_fields('fpc_settings_group');
            do_settings_sections('fpc-settings');
            submit_button();
            ?>
        </form>
        
        <div class="fpc-settings-section">
            <h2>插件使用说明</h2>
            <ol>
                <li>在产品编辑页面的"定制设置"部分配置产品定制选项</li>
                <li>设置价格规则和生产参数映射</li>
                <li>客户在前端选择定制选项并下单</li>
                <li>在"定制订单"页面查看和管理订单</li>
                <li>导出生产指令到生产系统</li>
            </ol>
        </div>
    </div>
    <?php
}

/**
 * 渲染订单管理页面
 */
public static function render_orders_page() {
    global $wpdb;
    
    // 获取定制订单
    $table_name = $wpdb->prefix . 'fpc_customizations';
    $orders = $wpdb->get_results(
        "SELECT c.*, o.post_status as order_status 
         FROM $table_name c 
         LEFT JOIN {$wpdb->posts} o ON c.order_id = o.ID 
         ORDER BY c.created_at DESC",
        ARRAY_A
    );
    ?>
    <div class="wrap">
        <h1>定制订单管理</h1>
        
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>订单号</th>
                    <th>产品</th>
                    <th>定制选项</th>
                    <th>价格</th>
                    <th>状态</th>
                    <th>下单时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): 
                    $product = wc_get_product($order['product_id']);
                    $customization_data = json_decode($order['customization_data'], true);
                ?>
                <tr>
                    <td>
                        <a href="<?php echo get_edit_post_link($order['order_id']); ?>">
                            #<?php echo $order['order_id']; ?>
                        </a>
                    </td>
                    <td><?php echo $product ? $product->get_name() : '产品已删除'; ?></td>
                    <td>
                        <?php
                        if ($customization_data) {
                            echo '<ul>';
                            foreach ($customization_data as $key => $value) {
                                if ($key !== 'quantity' && !empty($value)) {
                                    echo '<li>' . esc_html($key) . ': ' . esc_html($value) . '</li>';
                                }
                            }
                            echo '</ul>';
                        }
                        ?>
                    </td>
                    <td><?php echo wc_price($order['calculated_price']); ?></td>
                    <td>
                        <span class="fpc-status-<?php echo esc_attr($order['status']); ?>">
                            <?php echo self::get_status_label($order['status']); ?>
                        </span>
                    </td>
                    <td><?php echo date('Y-m-d H:i', strtotime($order['created_at'])); ?></td>
                    <td>
                        <button class="button button-small view-instructions" 
                                data-order-id="<?php echo $order['id']; ?>">
                            查看生产指令
                        </button>
                        <?php if ($order['status'] == 'pending'): ?>
                        <button class="button button-small mark-in-production" 
                                data-order-id="<?php echo $order['id']; ?>">
                            
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5698.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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