首页 / 教程文章 / WordPress文创商品柔性预售与反向定制插件集成教程

WordPress文创商品柔性预售与反向定制插件集成教程

WordPress文创商品柔性预售与反向定制插件集成教程

一、前言:文创电商的新趋势

在文创产业蓬勃发展的今天,个性化定制和预售模式已成为行业新趋势。WordPress作为全球最流行的内容管理系统,通过插件扩展可以轻松实现文创商品的柔性预售与反向定制功能。本教程将详细介绍如何通过集成专业插件,为您的WordPress文创电商网站添加这些高级功能。

柔性预售允许创作者根据用户预定量调整生产计划,降低库存风险;反向定制则让消费者参与设计过程,实现真正的个性化产品。这两种模式的结合,将为您的文创业务带来全新增长点。

二、环境准备与插件选择

2.1 系统要求

在开始之前,请确保您的WordPress环境满足以下要求:

  • WordPress 5.8或更高版本
  • PHP 7.4或更高版本
  • MySQL 5.6或更高版本
  • 已安装WooCommerce插件(基础电商功能)

2.2 推荐插件组合

为实现完整功能,我们建议使用以下插件组合:

  1. WooCommerce - 基础电商框架
  2. Product Add-Ons - 产品定制选项
  3. Pre-Orders for WooCommerce - 预售功能
  4. Custom Product Designer - 可视化定制工具

2.3 插件安装与激活

通过WordPress后台安装并激活上述插件:

/**
 * 检查必要插件是否激活
 * 此代码可添加到主题的functions.php文件中
 */
function check_required_plugins() {
    $required_plugins = array(
        'woocommerce/woocommerce.php' => 'WooCommerce',
        'woocommerce-product-addons/woocommerce-product-addons.php' => 'Product Add-Ons',
        'woocommerce-pre-orders/woocommerce-pre-orders.php' => 'Pre-Orders for WooCommerce',
        'custom-product-designer/custom-product-designer.php' => 'Custom Product Designer'
    );
    
    $inactive_plugins = array();
    
    foreach ($required_plugins as $plugin_path => $plugin_name) {
        if (!is_plugin_active($plugin_path)) {
            $inactive_plugins[] = $plugin_name;
        }
    }
    
    if (!empty($inactive_plugins)) {
        add_action('admin_notices', function() use ($inactive_plugins) {
            echo '<div class="notice notice-error">';
            echo '<p>文创定制功能需要以下插件:<strong>' . implode(', ', $inactive_plugins) . '</strong>。请安装并激活这些插件。</p>';
            echo '</div>';
        });
    }
}
add_action('admin_init', 'check_required_plugins');

三、配置预售功能

3.1 基础预售设置

进入WooCommerce → 设置 → 预售,进行基础配置:

/**
 * 预售产品自定义设置
 * 添加到主题的functions.php文件
 */
function custom_pre_order_settings($product) {
    // 检查是否为预售产品
    if (WC_Pre_Orders_Product::product_can_be_pre_ordered($product)) {
        // 设置预售结束时间(示例:30天后)
        $availability_date = date('Y-m-d H:i:s', strtotime('+30 days'));
        
        // 更新预售信息
        update_post_meta($product->get_id(), '_wc_pre_orders_availability_datetime', $availability_date);
        
        // 设置预售价格(比正常价格低10%)
        $regular_price = $product->get_regular_price();
        $pre_order_price = $regular_price * 0.9;
        update_post_meta($product->get_id(), '_wc_pre_orders_price', $pre_order_price);
        
        // 设置预售按钮文字
        update_post_meta($product->get_id(), '_wc_pre_orders_pre_order_button_text', '立即预订(享受早鸟价)');
    }
}
add_action('woocommerce_process_product_meta', 'custom_pre_order_settings');

3.2 预售阈值管理

实现基于预定数量的动态生产决策:

/**
 * 预售阈值检查与通知
 */
class PreOrderThresholdManager {
    private $thresholds = array(
        'low' => 50,     // 最低生产数量
        'medium' => 100, // 建议生产数量
        'high' => 200    // 最大生产数量
    );
    
    /**
     * 检查产品是否达到生产阈值
     * @param int $product_id 产品ID
     * @return array 阈值状态
     */
    public function check_threshold($product_id) {
        $pre_order_count = $this->get_pre_order_count($product_id);
        
        $status = array(
            'current_count' => $pre_order_count,
            'reached_low' => $pre_order_count >= $this->thresholds['low'],
            'reached_medium' => $pre_order_count >= $this->thresholds['medium'],
            'reached_high' => $pre_order_count >= $this->thresholds['high'],
            'remaining_to_medium' => max(0, $this->thresholds['medium'] - $pre_order_count)
        );
        
        return $status;
    }
    
    /**
     * 获取预售数量
     */
    private function get_pre_order_count($product_id) {
        global $wpdb;
        
        $count = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$wpdb->prefix}wc_pre_orders 
            WHERE product_id = %d 
            AND status IN ('active', 'completed')
        ", $product_id));
        
        return (int)$count;
    }
    
    /**
     * 显示预售进度条
     */
    public function display_progress_bar($product_id) {
        $status = $this->check_threshold($product_id);
        $percentage = min(100, ($status['current_count'] / $this->thresholds['high']) * 100);
        
        ob_start();
        ?>
        <div class="pre-order-progress">
            <h4>预售进度</h4>
            <div class="progress-bar">
                <div class="progress-fill" style="width: <?php echo $percentage; ?>%"></div>
            </div>
            <p>已预订:<?php echo $status['current_count']; ?> 件</p>
            <p>距离建议生产目标还差:<?php echo $status['remaining_to_medium']; ?> 件</p>
            <?php if ($status['reached_low']): ?>
                <p class="success">✓ 已达到最低生产数量,商品将会生产!</p>
            <?php endif; ?>
        </div>
        <style>
            .pre-order-progress { margin: 20px 0; padding: 15px; border: 1px solid #ddd; }
            .progress-bar { height: 20px; background: #f0f0f0; border-radius: 10px; overflow: hidden; }
            .progress-fill { height: 100%; background: linear-gradient(90deg, #4CAF50, #8BC34A); transition: width 0.3s; }
            .success { color: #4CAF50; font-weight: bold; }
        </style>
        <?php
        return ob_get_clean();
    }
}

// 在产品页面显示进度条
add_action('woocommerce_single_product_summary', function() {
    global $product;
    $manager = new PreOrderThresholdManager();
    echo $manager->display_progress_bar($product->get_id());
}, 25);

四、实现反向定制功能

4.1 产品定制选项配置

使用Product Add-Ons插件创建定制选项:

/**
 * 为文创产品添加定制选项
 */
function add_cultural_product_options($product_id) {
    // 检查是否为文创产品分类
    if (has_term('cultural-products', 'product_cat', $product_id)) {
        
        // 添加个性化文字选项
        $text_option = array(
            'name' => 'personalized_text',
            'title' => '个性化文字',
            'type' => 'custom_text',
            'required' => false,
            'price' => 0,
            'description' => '最多20个字符',
            'max_chars' => 20
        );
        
        // 添加图案选择选项
        $design_option = array(
            'name' => 'design_selection',
            'title' => '选择设计图案',
            'type' => 'select',
            'required' => true,
            'options' => array(
                array('label' => '传统纹样', 'price' => 0),
                array('label' => '现代抽象', 'price' => 50),
                array('label' => '定制图案上传', 'price' => 100)
            )
        );
        
        // 添加材质选择
        $material_option = array(
            'name' => 'material_type',
            'title' => '选择材质',
            'type' => 'radio',
            'required' => true,
            'options' => array(
                array('label' => '环保棉麻', 'price' => 0),
                array('label' => '优质丝绸', 'price' => 150),
                array('label' => '手工宣纸', 'price' => 200)
            )
        );
        
        // 保存选项到产品
        $options = array($text_option, $design_option, $material_option);
        update_post_meta($product_id, '_product_addons', $options);
    }
}
add_action('save_post_product', 'add_cultural_product_options');

4.2 可视化定制器集成

集成Custom Product Designer插件:

/**
 * 增强可视化定制功能
 */
class EnhancedProductDesigner {
    
    /**
     * 初始化定制器设置
     */
    public function init_designer($product_id) {
        // 基础配置
        $designer_config = array(
            'product_id' => $product_id,
            'canvas_width' => 800,
            'canvas_height' => 600,
            'enable_text' => true,
            'enable_images' => true,
            'enable_shapes' => true,
            'default_colors' => array('#FF5733', '#33FF57', '#3357FF', '#F0E68C'),
            'templates' => $this->get_design_templates()
        );
        
        // 保存配置
        update_post_meta($product_id, '_product_designer_config', $designer_config);
        
        return $designer_config;
    }
    
    /**
     * 获取设计模板
     */
    private function get_design_templates() {
        return array(
            array(
                'name' => '传统风格',
                'thumbnail' => get_template_directory_uri() . '/design-templates/traditional.jpg',
                'layers' => array(
                    array('type' => 'background', 'value' => '#F5F5DC'),
                    array('type' => 'pattern', 'value' => 'traditional-pattern.png')
                )
            ),
            array(
                'name' => '现代风格',
                'thumbnail' => get_template_directory_uri() . '/design-templates/modern.jpg',
                'layers' => array(
                    array('type' => 'background', 'value' => '#FFFFFF'),
                    array('type' => 'pattern', 'value' => 'geometric-pattern.png')
                )
            )
        );
    }
    
    /**
     * 在前端显示定制器
     */
    public function display_designer($product_id) {
        $config = get_post_meta($product_id, '_product_designer_config', true);
        
        if (empty($config)) {
            $config = $this->init_designer($product_id);
        }
        
        ob_start();
        ?>
        <div id="product-designer-container" data-config='<?php echo json_encode($config); ?>'>
            <div class="designer-header">
                <h3>产品定制设计器</h3>
                <div class="designer-tools">
                    <button class="tool-btn" data-tool="text">添加文字</button>
                    <button class="tool-btn" data-tool="image">上传图片</button>
                    <button class="tool-btn" data-tool="shape">添加形状</button>
                    <input type="color" id="color-picker" value="#FF5733">
                </div>
            </div>
            
            <div class="designer-body">
                <div class="canvas-container">
                    <canvas id="design-canvas" width="<?php echo $config['canvas_width']; ?>" 
                            height="<?php echo $config['canvas_height']; ?>"></canvas>
                </div>
                
                <div class="templates-sidebar">
                    <h4>设计模板</h4>
                    <?php foreach ($config['templates'] as $template): ?>
                        <div class="template-item" data-template='<?php echo json_encode($template); ?>'>
                            <img src="<?php echo $template['thumbnail']; ?>" alt="<?php echo $template['name']; ?>">
                            <span><?php echo $template['name']; ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="designer-footer">
                <button id="save-design" class="button-primary">保存设计</button>
                <button id="reset-design" class="button">重置</button>
                <input type="hidden" id="design-data" name="design_data">
            </div>
        </div>
        
        <script>
        // 初始化设计器JavaScript代码
        jQuery(document).ready(function($) {
            const container = $('#product-designer-container');
            const config = container.data('config');
            const canvas = document.getElementById('design-canvas');
            const ctx = canvas.getContext('2d');
            
            // 初始化画布
            ctx.fillStyle = '#FFFFFF';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 工具事件处理
            $('.tool-btn').on('click', function() {
                const tool = $(this).data('tool');
                activateTool(tool);
            });
            
            // 模板选择
            $('.template-item').on('click', function() {
                const template = $(this).data('template');
                applyTemplate(template);
            });
            
            // 保存设计
            $('#save-design').on('click', function() {
                const designData = canvas.toDataURL('image/png');
                $('#design-data').val(designData);
                alert('设计已保存!');
            });
            
            function activateTool(tool) {
                console.log('激活工具:', tool);
                // 这里添加具体的工具实现逻辑
            }
            
            function applyTemplate(template) {
                console.log('应用模板:', template);
                // 这里添加模板应用逻辑
            }
        });
        </script>
        
        <style>
        #product-designer-container { border: 1px solid #ddd; padding: 20px; margin: 20px 0; }
        .designer-header { display: flex; justify-content: space-between; margin-bottom: 15px; }
        .designer-tools button { margin-right: 10px; padding: 5px 15px; }
        .designer-body { display: flex; gap: 20px; }
        .canvas-container { flex: 3; border: 1px solid #ccc; }
        .templates-sidebar { flex: 1; }
        .template-item { margin-bottom: 10px; cursor: pointer; }
        .template-item img { width: 100%; height: auto; }
        .designer-footer { margin-top: 15px; text-align: right; }
        </style>
        <?php
        
        return ob_get_clean();
    }
}

// 在产品页面显示定制器
add_action('woocommerce_before_add_to_cart_button', function() {
    global $product;
    if (has_term('cultural-products', 'product_cat', $product->get_id())) {
        $designer = new EnhancedProductDesigner();
        echo $designer->display_designer($product->get_id());
    }
});

五、订单处理与生产管理

5.1 定制订单处理流程

/**
 * 处理定制订单
 */
class CustomOrderProcessor {
    
    /**
     * 处理新订单
     */
    public function process_custom_order($order_id) {
        $order = wc_get_order($order_id);
        
        foreach ($order->get_items() as $item) {
            $product_id = $item->get_product_id();
            
            // 检查是否为定制产品
            if ($this->is_custom_product($product_id)) {
                // 获取定制数据
                $custom_data = $this->extract_custom_data($item);
                
                // 生成生产指令
                $production_guide = $this->generate_production_guide($custom_data);
                
                // 保存到订单备注
                $order->add_order_note('定制要求:' . $production_guide);
                
                // 发送到生产队列
                $this->add_to_production_queue($order_id, $product_id, $custom_data);
            }
        }
    }
    
    /**
     * 提取定制数据
     */
    private function extract_custom_data($item) {
        $custom_data = array();
        
        // 从订单项元数据中提取定制信息
        foreach ($item->get_meta_data() as $meta) {
            if (in_array($meta->key, array('personalized_text', 'design_selection', 'material_type', 'design_data'))) {
                $custom_data[$meta->key] = $meta->value;
            }
        }
        
        return $custom_data;
    }
    
    /**
     * 生成生产指南
     */
    private function generate_production_guide($custom_data) {
        $guide = "生产指令:n";
        
        if (!empty($custom_data['personalized_text'])) {
            $guide .= "个性化文字:" . $custom_data['personalized_text'] . "n";
        }
        
        if (!empty($custom_data['design_selection'])) {
            $guide .= "设计图案:" . $custom_data['design_selection'] . "n";
        }
        
        if (!empty($custom_data['material_type'])) {
            $guide .= "材质选择:" . $custom_data['material_type'] . "n";
        }
        
        if (!empty($custom_data['design_data'])) {
        $guide .= "自定义设计图已上传至生产系统n";
    }
    
    return $guide;
}

/**
 * 添加到生产队列
 */
private function add_to_production_queue($order_id, $product_id, $custom_data) {
    global $wpdb;
    
    $queue_data = array(
        'order_id' => $order_id,
        'product_id' => $product_id,
        'custom_data' => json_encode($custom_data),
        'status' => 'pending',
        'created_at' => current_time('mysql'),
        'estimated_completion' => date('Y-m-d H:i:s', strtotime('+7 days'))
    );
    
    $wpdb->insert(
        $wpdb->prefix . 'custom_production_queue',
        $queue_data
    );
    
    // 发送生产通知
    $this->send_production_notification($order_id, $queue_data['estimated_completion']);
}

/**
 * 发送生产通知
 */
private function send_production_notification($order_id, $completion_date) {
    $order = wc_get_order($order_id);
    $customer_email = $order->get_billing_email();
    
    $subject = '您的定制订单已进入生产流程';
    $message = "
        <h3>订单生产确认通知</h3>
        <p>您的定制订单 #{$order_id} 已进入生产队列。</p>
        <p><strong>预计完成日期:</strong>{$completion_date}</p>
        <p>生产过程中如有任何问题,我们会及时与您联系。</p>
        <p>感谢您选择我们的定制服务!</p>
    ";
    
    wp_mail($customer_email, $subject, $message, array('Content-Type: text/html; charset=UTF-8'));
}

/**
 * 检查是否为定制产品
 */
private function is_custom_product($product_id) {
    return has_term('cultural-products', 'product_cat', $product_id) || 
           get_post_meta($product_id, '_is_customizable', true) === 'yes';
}

}

// 订单状态变更时触发处理
add_action('woocommerce_order_status_processing', function($order_id) {

$processor = new CustomOrderProcessor();
$processor->process_custom_order($order_id);

});

// 创建生产队列表
register_activation_hook(__FILE__, function() {

global $wpdb;

$table_name = $wpdb->prefix . 'custom_production_queue';
$charset_collate = $wpdb->get_charset_collate();

$sql = "CREATE TABLE IF NOT EXISTS $table_name (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    order_id bigint(20) NOT NULL,
    product_id bigint(20) NOT NULL,
    custom_data longtext NOT NULL,
    status varchar(50) NOT NULL DEFAULT 'pending',
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    estimated_completion datetime NOT NULL,
    completed_at datetime NULL,
    production_notes text,
    PRIMARY KEY (id),
    KEY order_id (order_id),
    KEY status (status)
) $charset_collate;";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);

});


### 5.2 生产状态跟踪与更新

/**

  • 生产状态管理系统
    */

class ProductionStatusManager {


/**
 * 更新生产状态
 */
public function update_production_status($queue_id, $status, $notes = '') {
    global $wpdb;
    
    $update_data = array('status' => $status);
    
    if ($status === 'completed') {
        $update_data['completed_at'] = current_time('mysql');
    }
    
    if (!empty($notes)) {
        $update_data['production_notes'] = $notes;
    }
    
    $wpdb->update(
        $wpdb->prefix . 'custom_production_queue',
        $update_data,
        array('id' => $queue_id)
    );
    
    // 获取订单信息并通知客户
    $order_id = $wpdb->get_var($wpdb->prepare(
        "SELECT order_id FROM {$wpdb->prefix}custom_production_queue WHERE id = %d",
        $queue_id
    ));
    
    if ($order_id) {
        $this->notify_customer_status_change($order_id, $status, $notes);
    }
}

/**
 * 通知客户状态变更
 */
private function notify_customer_status_change($order_id, $status, $notes) {
    $order = wc_get_order($order_id);
    $customer_email = $order->get_billing_email();
    
    $status_labels = array(
        'designing' => '设计制作中',
        'printing' => '印刷生产中',
        'assembling' => '组装中',
        'quality_check' => '质量检测中',
        'completed' => '已完成生产',
        'shipped' => '已发货'
    );
    
    $subject = "订单 #{$order_id} 生产状态更新";
    $message = "
        <h3>生产状态更新通知</h3>
        <p>您的定制订单 #{$order_id} 状态已更新:</p>
        <p><strong>新状态:</strong>{$status_labels[$status]}</p>
    ";
    
    if (!empty($notes)) {
        $message .= "<p><strong>生产备注:</strong>{$notes}</p>";
    }
    
    if ($status === 'completed') {
        $message .= "<p>您的商品已完成生产,即将安排发货。</p>";
    }
    
    wp_mail($customer_email, $subject, $message, array('Content-Type: text/html; charset=UTF-8'));
}

/**
 * 显示生产进度跟踪
 */
public function display_production_tracking($order_id) {
    global $wpdb;
    
    $production_data = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}custom_production_queue 
         WHERE order_id = %d ORDER BY id DESC LIMIT 1",
        $order_id
    ));
    
    if (!$production_data) {
        return '<p>暂无生产信息</p>';
    }
    
    $status_steps = array(
        'pending' => array('label' => '待处理', 'percent' => 10),
        'designing' => array('label' => '设计中', 'percent' => 30),
        'printing' => array('label' => '印刷中', 'percent' => 50),
        'assembling' => array('label' => '组装中', 'percent' => 70),
        'quality_check' => array('label' => '质检中', 'percent' => 90),
        'completed' => array('label' => '已完成', 'percent' => 100)
    );
    
    ob_start();
    ?>
    <div class="production-tracking">
        <h3>生产进度跟踪</h3>
        <div class="tracking-timeline">
            <?php foreach ($status_steps as $status => $step): ?>
                <div class="timeline-step <?php echo $status === $production_data->status ? 'active' : ''; ?> 
                     <?php echo array_search($status, array_keys($status_steps)) < array_search($production_data->status, array_keys($status_steps)) ? 'completed' : ''; ?>">
                    <div class="step-icon"></div>
                    <div class="step-label"><?php echo $step['label']; ?></div>
                    <div class="step-date">
                        <?php if ($status === $production_data->status): ?>
                            进行中
                        <?php elseif (array_search($status, array_keys($status_steps)) < array_search($production_data->status, array_keys($status_steps))): ?>
                            <?php echo date('m/d', strtotime($production_data->created_at . ' +' . ($step['percent']/20) . ' days')); ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="tracking-details">
            <p><strong>订单号:</strong>#<?php echo $order_id; ?></p>
            <p><strong>当前状态:</strong><?php echo $status_steps[$production_data->status]['label']; ?></p>
            <p><strong>预计完成:</strong><?php echo date('Y年m月d日', strtotime($production_data->estimated_completion)); ?></p>
            
            <?php if ($production_data->production_notes): ?>
                <div class="production-notes">
                    <strong>生产备注:</strong>
                    <p><?php echo nl2br($production_data->production_notes); ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <style>
    .production-tracking { 
        padding: 20px; 
        border: 1px solid #e0e0e0; 
        border-radius: 8px; 
        margin: 20px 0; 
        background: #f9f9f9; 
    }
    .tracking-timeline {
        display: flex;
        justify-content: space-between;
        position: relative;
        margin-bottom: 30px;
    }
    .tracking-timeline::before {
        content: '';
        position: absolute;
        top: 15px;
        left: 0;
        right: 0;
        height: 3px;
        background: #e0e0e0;
        z-index: 1;
    }
    .timeline-step {
        position: relative;
        z-index: 2;
        text-align: center;
        flex: 1;
    }
    .step-icon {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: #e0e0e0;
        margin: 0 auto 10px;
        position: relative;
    }
    .timeline-step.completed .step-icon {
        background: #4CAF50;
    }
    .timeline-step.active .step-icon {
        background: #2196F3;
        animation: pulse 2s infinite;
    }
    .timeline-step.completed .step-icon::after {
        content: '✓';
        color: white;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .step-label {
        font-size: 12px;
        color: #666;
        margin-bottom: 5px;
    }
    .timeline-step.active .step-label {
        color: #2196F3;
        font-weight: bold;
    }
    .step-date {
        font-size: 11px;
        color: #999;
    }
    .tracking-details {
        background: white;
        padding: 15px;
        border-radius: 5px;
        border: 1px solid #e0e0e0;
    }
    .production-notes {
        margin-top: 10px;
        padding: 10px;
        background: #fffde7;
        border-left: 4px solid #ffd600;
    }
    @keyframes pulse {
        0% { box-shadow: 0 0 0 0 rgba(33, 150, 243, 0.4); }
        70% { box-shadow: 0 0 0 10px rgba(33, 150, 243, 0); }
        100% { box-shadow: 0 0 0 0 rgba(33, 150, 243, 0); }
    }
    </style>
    <?php
    return ob_get_clean();
}

}

// 在订单详情页显示生产跟踪
add_action('woocommerce_view_order', function($order_id) {

$status_manager = new ProductionStatusManager();
echo $status_manager->display_production_tracking($order_id);

}, 15);


## 六、数据统计与优化建议

### 6.1 销售与生产数据分析

/**

  • 文创产品销售分析
    */

class CulturalProductsAnalytics {


/**
 * 获取预售数据分析
 */
public function get_preorder_analytics($start_date, $end_date) {
    global $wpdb;
    
    $results = $wpdb->get_results($wpdb->prepare("
        SELECT 
            p.ID as product_id,
            p.post_title as product_name,
            COUNT(DISTINCT po.order_id) as preorder_count,
            SUM(oi.meta_value) as total_revenue,
            AVG(oi.meta_value) as avg_order_value,
            MIN(po.created_at) as first_preorder,
            MAX(po.created_at) as last_preorder
        FROM {$wpdb->prefix}wc_pre_orders po
        INNER JOIN {$wpdb->prefix}posts p ON po.product_id = p.ID
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta oi ON oi.order_item_id = po.order_item_id
        WHERE oi.meta_key = '_line_total'
        AND po.created_at BETWEEN %s AND %s
        AND p.post_type = 'product'
        GROUP BY p.ID
        ORDER BY preorder_count DESC
    ", $start_date, $end_date));
    
    return $results;
}

/**
 * 获取定制选项受欢迎程度
 */
public function get_customization_popularity() {
    global $wpdb;
    
    $data = $wpdb->get_results("
        SELECT 
            meta_key,
            meta_value as option_value,
            COUNT(*) as selection_count
        FROM {$wpdb->prefix}woocommerce_order_itemmeta
        WHERE meta_key IN ('personalized_text', 'design_selection', 'material_type')
        GROUP BY meta_key, meta_value
        ORDER BY meta_key, selection_count DESC
    ");
    
    $analysis = array();
    foreach ($data as $row) {
        if (!isset($analysis[$row->meta_key])) {
            $analysis[$row->meta_key] = array();
        }
        $analysis[$row->meta_key][] = array(
            'option' => $row->option_value,
            'count' => $row->selection_count
        );
    }
    
    return $analysis;
}

/**
 * 生成优化建议
 */
public function generate_optimization_suggestions() {
    $suggestions = array();
    
    // 分析预售数据
    $preorder_data = $this->get_preorder_analytics(
        date('Y-m-01', strtotime('-1 month')),
        date('Y-m-t')
    );
    
    // 分析定制偏好
    $customization_data = $this->get_customization_popularity();
    
    // 生成建议
    if (!empty($preorder_data)) {
        $top_product = $preorder_data[0];
        
        if ($top_product->preorder_count > 100) {
            $suggestions[] = array(
                'type' => 'production',
                'title' => '增加热门产品库存',
                'description' => "产品'{$top_product->product_name}'预售量已达{$top_product->preorder_count}件,建议增加生产批量以降低成本。",
                'priority' => 'high'
            );
        }
    }
    
    if (isset($customization_data['design_selection'])) {
        $popular_designs = array_slice($customization_data['design_selection'], 0, 3);
        
        $suggestions[] = array(
            'type' => 'design',
            'title' => '优化设计选项',
            'description' => '最受欢迎的设计图案:' . implode('、', array_column($popular_designs, 'option')),
            'priority' => 'medium'
        );
    }
    
    return $suggestions;
}

/**
 * 显示分析仪表板
 */
public function display_analytics_dashboard() {
    $suggestions = $this->generate_optimization_suggestions();
    
    ob_start();
    ?>
    <div class="cultural-analytics-dashboard">
        <h2>文创产品分析仪表板</h2>
        
        <div class="dashboard-grid">
            <div class="dashboard-card">
                <h3>本月预售统计</h3>
                <?php 
                $monthly_data = $this->get_preorder_analytics(
                    date('Y-m-01'),
                    date('Y-m-t')
                );
                $total_preorders = array_sum(array_column($monthly_data, 'preorder_count'));
                $total_revenue = array_sum(array_column($monthly_data, 'total_revenue'));
                ?>
                <div class="stat-number"><?php echo $total_preorders; ?> 件</div>
                <div class="stat-label">预售订单数</div>
                <div class="stat-number">¥<?php echo number_format($total_revenue, 2); ?></div>
                <div class="stat-label">预售金额</div>
            </div>
            
            <div class="dashboard-card">
                <h3>定制偏好分析</h3>
                <?php 
                $customization_data = $this->get_customization_popularity();
                if (isset($customization_data['material_type'])) {
                    $top_material = $customization_data['material_type'][0];
                    echo "<p>最受欢迎材质:<strong>{$top_material['option']}</strong></p>";
                    echo "<p>选择次数:{$top_material['count']}次</p>";
                }
                ?>
            </div>
        </div>
        
        <div class="suggestions-section">
            <h3>优化建议</h3>
            <?php foreach ($suggestions as $suggestion): ?>
                <div class="suggestion-item priority-<?php echo $suggestion['priority']; ?>">
                    <span class="suggestion-badge"><?php echo strtoupper($suggestion['priority']); ?></span>
                    <h4><?php echo $suggestion['title']; ?></h4>
                    <p><?php echo $suggestion['description']; ?></p>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <style>
    .cultural-analytics-dashboard { padding: 20px; }
    .dashboard-grid { 
        display: grid; 
        grid-template-column
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/6353.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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