首页 / 教程文章 / WordPress文创产品柔性众筹与预售插件集成教程

WordPress文创产品柔性众筹与预售插件集成教程

WordPress文创产品柔性众筹与预售插件集成教程

一、前言:文创产品与柔性供应链的数字化机遇

在文创产业蓬勃发展的今天,创作者们面临着产品开发资金压力和市场风险的双重挑战。柔性众筹与预售模式为文创产品提供了创新的解决方案——通过预售测试市场反应,根据订单量调整生产规模,实现"按需生产"。本教程将详细介绍如何在WordPress网站中集成柔性众筹与预售功能,帮助文创创作者搭建专业的数字化销售平台。

二、系统环境准备与插件选择

2.1 基础环境要求

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

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

2.2 核心插件选择

我们将使用以下插件组合实现柔性众筹与预售功能:

  1. WooCommerce - 基础电商框架
  2. WooCommerce Pre-Orders - 预售功能核心
  3. Crowdfunding for WooCommerce - 众筹功能扩展
  4. Advanced Custom Fields - 自定义字段管理

三、插件安装与基础配置

3.1 安装与激活插件

在WordPress后台完成插件安装:

/**
 * 插件依赖检查与自动安装
 * 将此代码添加到主题的functions.php文件中
 * 实现插件依赖的自动检查与安装提示
 */
function check_plugin_dependencies() {
    $required_plugins = array(
        'woocommerce/woocommerce.php' => 'WooCommerce',
        'woocommerce-pre-orders/woocommerce-pre-orders.php' => 'WooCommerce Pre-Orders',
        'crowdfunding-for-woocommerce/crowdfunding.php' => 'Crowdfunding for WooCommerce',
        'advanced-custom-fields/acf.php' => 'Advanced Custom Fields'
    );
    
    $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>文创众筹系统提示:</strong> 需要安装并激活以下插件:';
            echo implode(', ', $inactive_plugins) . '</p>';
            echo '</div>';
        });
    }
}
add_action('admin_init', 'check_plugin_dependencies');

3.2 基础WooCommerce配置

  1. 进入WooCommerce → 设置 → 产品
  2. 启用库存管理功能
  3. 设置预售/众筹产品分类
  4. 配置支付网关(推荐支付宝、微信支付)

四、预售功能实现

4.1 创建预售产品

/**
 * 创建预售产品类型
 * 扩展WooCommerce产品类型,添加预售专属功能
 */
function register_preorder_product_type() {
    class WC_Product_Preorder extends WC_Product_Simple {
        public function __construct($product) {
            $this->product_type = 'preorder';
            parent::__construct($product);
        }
        
        // 获取预售结束时间
        public function get_preorder_end_date() {
            return get_post_meta($this->get_id(), '_preorder_end_date', true);
        }
        
        // 检查是否在预售期内
        public function is_preorder_active() {
            $end_date = $this->get_preorder_end_date();
            if (!$end_date) return false;
            
            $current_time = current_time('timestamp');
            $end_timestamp = strtotime($end_date);
            
            return $current_time <= $end_timestamp;
        }
        
        // 获取预售价格
        public function get_preorder_price() {
            $price = get_post_meta($this->get_id(), '_preorder_price', true);
            return $price ? $price : $this->get_price();
        }
    }
}
add_action('init', 'register_preorder_product_type');

/**
 * 添加预售产品到产品类型选择
 */
function add_preorder_product_type($types) {
    $types['preorder'] = __('文创预售产品', 'textdomain');
    return $types;
}
add_filter('product_type_selector', 'add_preorder_product_type');

4.2 预售产品设置界面

/**
 * 添加预售产品设置选项卡
 */
function preorder_product_tabs($tabs) {
    $tabs['preorder'] = array(
        'label'    => __('预售设置', 'textdomain'),
        'target'   => 'preorder_product_data',
        'class'    => array('show_if_preorder'),
        'priority' => 21,
    );
    return $tabs;
}
add_filter('woocommerce_product_data_tabs', 'preorder_product_tabs');

/**
 * 预售设置面板内容
 */
function preorder_product_panels() {
    global $post;
    ?>
    <div id="preorder_product_data" class="panel woocommerce_options_panel">
        <div class="options_group">
            <?php
            // 预售结束日期
            woocommerce_wp_text_input(array(
                'id' => '_preorder_end_date',
                'label' => __('预售结束日期', 'textdomain'),
                'placeholder' => 'YYYY-MM-DD',
                'description' => __('设置预售截止日期', 'textdomain'),
                'desc_tip' => true,
                'type' => 'date',
            ));
            
            // 预售价格
            woocommerce_wp_text_input(array(
                'id' => '_preorder_price',
                'label' => __('预售价格', 'textdomain'),
                'placeholder' => __('如不设置则使用常规价格', 'textdomain'),
                'description' => __('预售期间的特惠价格', 'textdomain'),
                'desc_tip' => true,
                'type' => 'number',
                'custom_attributes' => array(
                    'step' => 'any',
                    'min' => '0'
                )
            ));
            
            // 预售目标数量
            woocommerce_wp_text_input(array(
                'id' => '_preorder_goal',
                'label' => __('预售目标数量', 'textdomain'),
                'placeholder' => '100',
                'description' => __('达到此数量后开始生产', 'textdomain'),
                'desc_tip' => true,
                'type' => 'number',
                'custom_attributes' => array(
                    'min' => '1'
                )
            ));
            ?>
        </div>
    </div>
    <?php
}
add_action('woocommerce_product_data_panes', 'preorder_product_panels');

/**
 * 保存预售产品设置
 */
function save_preorder_product_data($post_id) {
    $product = wc_get_product($post_id);
    
    // 保存预售结束日期
    if (isset($_POST['_preorder_end_date'])) {
        update_post_meta($post_id, '_preorder_end_date', sanitize_text_field($_POST['_preorder_end_date']));
    }
    
    // 保存预售价格
    if (isset($_POST['_preorder_price'])) {
        update_post_meta($post_id, '_preorder_price', wc_format_decimal($_POST['_preorder_price']));
    }
    
    // 保存预售目标
    if (isset($_POST['_preorder_goal'])) {
        update_post_meta($post_id, '_preorder_goal', absint($_POST['_preorder_goal']));
    }
}
add_action('woocommerce_process_product_meta_preorder', 'save_preorder_product_data');

五、众筹功能扩展

5.1 众筹进度显示

/**
 * 在商品页面显示众筹进度条
 */
function display_crowdfunding_progress() {
    global $product;
    
    if ($product->get_type() !== 'preorder') return;
    
    $goal = get_post_meta($product->get_id(), '_preorder_goal', true);
    $sold = get_post_meta($product->get_id(), '_preorder_sold', true) ?: 0;
    
    if (!$goal) return;
    
    $percentage = min(100, ($sold / $goal) * 100);
    ?>
    <div class="crowdfunding-progress" style="margin: 20px 0;">
        <h3><?php _e('众筹进度', 'textdomain'); ?></h3>
        <div class="progress-bar" style="width: 100%; height: 20px; background: #f0f0f0; border-radius: 10px; overflow: hidden;">
            <div class="progress-fill" style="width: <?php echo $percentage; ?>%; height: 100%; background: linear-gradient(90deg, #4CAF50, #8BC34A); transition: width 0.5s ease;"></div>
        </div>
        <div class="progress-info" style="display: flex; justify-content: space-between; margin-top: 10px;">
            <span><?php printf(__('已预售:%d/%d', 'textdomain'), $sold, $goal); ?></span>
            <span><?php echo round($percentage, 1); ?>%</span>
        </div>
        <?php if ($percentage >= 100): ?>
            <div class="goal-reached" style="color: #4CAF50; font-weight: bold; margin-top: 10px;">
                <?php _e('🎉 已达成众筹目标,即将开始生产!', 'textdomain'); ?>
            </div>
        <?php endif; ?>
    </div>
    <?php
}
add_action('woocommerce_single_product_summary', 'display_crowdfunding_progress', 25);

/**
 * 更新已售数量
 * 在订单状态变更时更新预售数量
 */
function update_preorder_sold_count($order_id, $old_status, $new_status) {
    $order = wc_get_order($order_id);
    
    // 只处理已完成或处理中的订单
    if (!in_array($new_status, array('processing', 'completed'))) return;
    
    foreach ($order->get_items() as $item) {
        $product_id = $item->get_product_id();
        $product = wc_get_product($product_id);
        
        if ($product->get_type() === 'preorder') {
            $sold = get_post_meta($product_id, '_preorder_sold', true) ?: 0;
            $quantity = $item->get_quantity();
            
            update_post_meta($product_id, '_preorder_sold', $sold + $quantity);
        }
    }
}
add_action('woocommerce_order_status_changed', 'update_preorder_sold_count', 10, 3);

六、柔性供应链集成

6.1 生产状态追踪

/**
 * 生产状态管理
 * 为预售产品添加生产状态追踪
 */
class Flexible_Production_Manager {
    private $product_id;
    
    public function __construct($product_id) {
        $this->product_id = $product_id;
    }
    
    // 获取当前生产状态
    public function get_production_status() {
        $status = get_post_meta($this->product_id, '_production_status', true);
        return $status ? $status : 'pending';
    }
    
    // 更新生产状态
    public function update_status($new_status, $notes = '') {
        $allowed_statuses = array(
            'pending'     => __('等待生产', 'textdomain'),
            'designing'   => __('设计中', 'textdomain'),
            'prototyping' => __('打样中', 'textdomain'),
            'producing'   => __('生产中', 'textdomain'),
            'qc_checking' => __('质检中', 'textdomain'),
            'packaging'   => __('包装中', 'textdomain'),
            'shipping'    => __('发货中', 'textdomain'),
            'completed'   => __('已完成', 'textdomain')
        );
        
        if (!array_key_exists($new_status, $allowed_statuses)) {
            return false;
        }
        
        $old_status = $this->get_production_status();
        update_post_meta($this->product_id, '_production_status', $new_status);
        
        // 记录状态变更历史
        $history = get_post_meta($this->product_id, '_production_history', true) ?: array();
        $history[] = array(
            'time'    => current_time('mysql'),
            'from'    => $old_status,
            'to'      => $new_status,
            'notes'   => $notes
        );
        
        update_post_meta($this->product_id, '_production_history', $history);
        
        // 发送状态更新通知
        $this->notify_status_change($new_status, $notes);
        
        return true;
    }
    
    // 通知相关用户
    private function notify_status_change($status, $notes) {
        // 获取所有预订了此产品的订单
        $orders = wc_get_orders(array(
            'status'   => array('processing', 'completed'),
            'meta_key' => '_contains_preorder',
            'meta_value' => $this->product_id
        ));
        
        foreach ($orders as $order) {
            $user_email = $order->get_billing_email();
            $subject = sprintf(__('您的文创产品生产状态已更新:%s', 'textdomain'), 
                get_the_title($this->product_id));
            
            $message = sprintf(__(
                "亲爱的顾客:nn" .
                "您预订的产品《%s》生产状态已更新:nn" .
                "新状态:%sn" .
                "更新说明:%snn" .
                "您可以通过以下链接查看最新状态:n" .
                "%snn" .
                "感谢您的支持!n" .
                "%s团队", 'textdomain'),
                get_the_title($this->product_id),
                $this->get_status_label($status),
                $notes,
                get_permalink($this->product_id),
                get_bloginfo('name')
            );
            
            wp_mail($user_email, $subject, $message);
        }
    }
    
    // 获取状态标签
    private function get_status_label($status) {
        $labels = array(
            'pending'     => __('等待生产', 'textdomain'),
            'designing'   => __('设计中', 'textdomain'),
            'prototyping' => __('打样中', 'textdomain'),
            'producing'   => __('生产中', 'textdomain'),
            'qc_checking' => __('质检中', 'textdomain'),
            'packaging'   => __('包装中', 'textdomain'),
            'shipping'    => __('发货中', 'textdomain'),
            'completed'   => __('已完成', 'textdomain')
        );
        
        return isset($labels[$status]) ? $labels[$status] : $status;
    }
}

七、前端展示优化

7.1 产品列表页标识

/**
 * 在产品列表页添加预售标识
 */
function add_preorder_badge_in_loop() {
    global $product;
    
    if ($product->get_type() === 'preorder') {
        $end_date = $product->get_preorder_end_date();
        
        if ($end_date && $product->is_preorder_active()) {
            $days_left = ceil((strtotime($end_date) - current_time('timestamp')) / DAY_IN_SECONDS);
            
            echo '<span class="preorder-badge" style="position: absolute; top: 10px; right: 10px; background: #FF5722; color: white; padding: 5px 10px; border-radius: 3px; font-size: 12px; z-index: 10;">';
            if ($days_left > 0) {
                printf(__('预售中(剩%d天)', 'textdomain'), $days_left);
            } else {
                _e('预售最后一天', 'textdomain');
            }
            echo '</span>';
        }
    }
}
add_action('woocommerce_before_shop_loop_item_title', 'add_preorder_badge_in_loop', 9);

7.2 产品详情页预售信息

/**
 * 在产品详情页显示预售详细信息
 */
function display_preorder_details() {
    global $product;
    
    if ($product->get_type() !== 'preorder') return;
    
    $end_date = $product->get_preorder_end_date();
    $goal = get_post_meta($product->get_id(), '_preorder_goal', true);
    $sold = get_post_meta($product->get_id(), '_preorder_sold', true) ?: 0;
    
    if (!$end_date) return;
    ?>
    <div class="preorder-details" style="background: #f8f9fa; padding: 20px; border-radius: 5px; margin: 20px 0;">
        <h3><?php _e('预售说明', 'textdomain'); ?></h3>
        <ul style="list-style: none; padding-left: 0;">
            <li style="margin-bottom: 10px;">✅ <?php _e('此产品为预售商品', 'textdomain'); ?></li>
            <li style="margin-bottom: 10px;">📅 <?php 
                printf(__('预售截止:%s', 'textdomain'), 
                    date_i18n(get_option('date_format'), strtotime($end_date)));
            ?></li>
            <li style="margin-bottom: 10px;">🎯 <?php 
                printf(__('生产目标:%d件(已达成%d件)', 'textdomain'), $goal, min($sold, $goal));
            ?></li>
            <li style="margin-bottom: 10px;">⏳ <?php _e('预计发货时间:达成目标后30-45天', 'textdomain'); ?></li>
            <li style="margin-bottom: 10px;">💡 <?php _e('柔性生产:根据实际订单量生产,避免浪费', 'textdomain'); ?></li>
        </ul>
        
        <?php if (!$product->is_preorder_active()): ?>

order-ended" style="color: #ff5722; font-weight: bold; padding: 10px; border: 1px solid #ff5722; border-radius: 3px;">

            <?php _e('预售已结束,感谢支持!', 'textdomain'); ?>
        </div>
    <?php endif; ?>
</div>
<?php

}
add_action('woocommerce_single_product_summary', 'display_preorder_details', 15);


## 八、订单管理与自动化流程

### 8.1 预售订单特殊处理

/**

  • 预售订单特殊标记与处理
    */

class Preorder_Order_Manager {


// 标记包含预售产品的订单
public static function mark_preorder_order($order_id) {
    $order = wc_get_order($order_id);
    $has_preorder = false;
    
    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        if ($product && $product->get_type() === 'preorder') {
            $has_preorder = true;
            // 记录订单中的预售产品
            add_post_meta($order_id, '_preorder_product_' . $product->get_id(), $item->get_quantity());
        }
    }
    
    if ($has_preorder) {
        // 标记订单包含预售产品
        update_post_meta($order_id, '_contains_preorder', 'yes');
        
        // 设置订单状态为"预售中"
        $order->update_status('preorder', __('订单包含预售商品', 'textdomain'));
        
        // 发送预售订单确认邮件
        self::send_preorder_confirmation($order);
    }
}

// 发送预售订单确认邮件
private static function send_preorder_confirmation($order) {
    $to = $order->get_billing_email();
    $subject = sprintf(__('您的文创预售订单确认 #%s', 'textdomain'), $order->get_order_number());
    
    $message = self::get_preorder_email_template($order);
    
    // 设置HTML邮件头
    $headers = array('Content-Type: text/html; charset=UTF-8');
    
    wp_mail($to, $subject, $message, $headers);
}

// 预售邮件模板
private static function get_preorder_email_template($order) {
    ob_start();
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title><?php _e('预售订单确认', 'textdomain'); ?></title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #4CAF50; color: white; padding: 20px; text-align: center; }
            .content { background: #f9f9f9; padding: 20px; }
            .order-details { background: white; padding: 15px; border-radius: 5px; margin: 15px 0; }
            .footer { text-align: center; margin-top: 20px; color: #666; font-size: 12px; }
            .preorder-notice { background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 15px 0; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1><?php _e('🎨 文创预售订单确认', 'textdomain'); ?></h1>
            </div>
            
            <div class="content">
                <p><?php printf(__('亲爱的 %s,', 'textdomain'), $order->get_billing_first_name()); ?></p>
                <p><?php _e('感谢您支持我们的文创产品!您的预售订单已确认。', 'textdomain'); ?></p>
                
                <div class="preorder-notice">
                    <h3>📋 <?php _e('预售说明', 'textdomain'); ?></h3>
                    <p><?php _e('您购买的是预售商品,我们将根据最终预售数量进行生产。', 'textdomain'); ?></p>
                    <p><?php _e('生产进度和发货时间将通过邮件通知您。', 'textdomain'); ?></p>
                </div>
                
                <div class="order-details">
                    <h3><?php _e('订单信息', 'textdomain'); ?></h3>
                    <p><strong><?php _e('订单号:', 'textdomain'); ?></strong> #<?php echo $order->get_order_number(); ?></p>
                    <p><strong><?php _e('订单日期:', 'textdomain'); ?></strong> <?php echo $order->get_date_created()->date_i18n(); ?></p>
                    <p><strong><?php _e('订单总额:', 'textdomain'); ?></strong> <?php echo $order->get_formatted_order_total(); ?></p>
                </div>
                
                <p><?php _e('您可以通过以下链接查看订单详情:', 'textdomain'); ?></p>
                <p><a href="<?php echo $order->get_view_order_url(); ?>" style="background: #4CAF50; color: white; padding: 10px 20px; text-decoration: none; border-radius: 3px; display: inline-block;">
                    <?php _e('查看订单详情', 'textdomain'); ?>
                </a></p>
            </div>
            
            <div class="footer">
                <p><?php echo get_bloginfo('name'); ?></p>
                <p><?php _e('如有任何问题,请回复此邮件或联系客服。', 'textdomain'); ?></p>
            </div>
        </div>
    </body>
    </html>
    <?php
    return ob_get_clean();
}

}

// 订单创建时检查预售产品
add_action('woocommerce_checkout_order_processed', array('Preorder_Order_Manager', 'mark_preorder_order'), 10, 1);


### 8.2 自动化生产触发

/**

  • 预售目标达成后的自动化处理
    */

class Production_Trigger {


// 检查并触发生产
public static function check_and_trigger_production($product_id) {
    $product = wc_get_product($product_id);
    
    if ($product->get_type() !== 'preorder') {
        return;
    }
    
    $goal = get_post_meta($product_id, '_preorder_goal', true);
    $sold = get_post_meta($product_id, '_preorder_sold', true) ?: 0;
    
    // 检查是否达到生产目标
    if ($sold >= $goal) {
        $already_triggered = get_post_meta($product_id, '_production_triggered', true);
        
        if (!$already_triggered) {
            // 标记生产已触发
            update_post_meta($product_id, '_production_triggered', current_time('mysql'));
            
            // 更新产品状态
            $production_manager = new Flexible_Production_Manager($product_id);
            $production_manager->update_status('designing', '预售目标已达成,开始设计阶段');
            
            // 发送生产开始通知
            self::notify_production_start($product_id);
            
            // 记录生产批次
            self::create_production_batch($product_id, $sold);
        }
    }
}

// 创建生产批次
private static function create_production_batch($product_id, $quantity) {
    $batch_data = array(
        'product_id'    => $product_id,
        'batch_number'  => 'BATCH-' . date('Ymd') . '-' . $product_id,
        'quantity'      => $quantity,
        'start_date'    => current_time('mysql'),
        'status'        => 'planned',
        'notes'         => sprintf(__('预售订单生产批次,共%d件', 'textdomain'), $quantity)
    );
    
    add_post_meta($product_id, '_production_batches', $batch_data);
    
    // 创建生产任务
    self::create_production_tasks($product_id, $batch_data);
}

// 创建生产任务
private static function create_production_tasks($product_id, $batch_data) {
    $tasks = array(
        array(
            'name' => __('设计确认', 'textdomain'),
            'duration' => 7, // 天数
            'responsible' => 'design_team'
        ),
        array(
            'name' => __('材料采购', 'textdomain'),
            'duration' => 10,
            'responsible' => 'purchasing_team'
        ),
        array(
            'name' => __('样品制作', 'textdomain'),
            'duration' => 5,
            'responsible' => 'production_team'
        ),
        array(
            'name' => __('批量生产', 'textdomain'),
            'duration' => 15,
            'responsible' => 'production_team'
        ),
        array(
            'name' => __('质量检查', 'textdomain'),
            'duration' => 3,
            'responsible' => 'qc_team'
        ),
        array(
            'name' => __('包装发货', 'textdomain'),
            'duration' => 5,
            'responsible' => 'shipping_team'
        )
    );
    
    $start_date = strtotime($batch_data['start_date']);
    
    foreach ($tasks as $task) {
        $task_data = array(
            'batch_number'  => $batch_data['batch_number'],
            'task_name'     => $task['name'],
            'start_date'    => date('Y-m-d', $start_date),
            'end_date'      => date('Y-m-d', $start_date + ($task['duration'] * DAY_IN_SECONDS)),
            'responsible'   => $task['responsible'],
            'status'        => 'pending'
        );
        
        add_post_meta($product_id, '_production_tasks', $task_data);
        
        $start_date += $task['duration'] * DAY_IN_SECONDS;
    }
}

// 通知生产开始
private static function notify_production_start($product_id) {
    $product = wc_get_product($product_id);
    $product_title = $product->get_title();
    
    // 通知管理员
    $admin_email = get_option('admin_email');
    $subject = sprintf(__('🎉 产品"%s"开始生产', 'textdomain'), $product_title);
    
    $message = sprintf(__(
        "产品信息:%sn" .
        "生产批次:BATCH-%s-%dn" .
        "生产数量:%d件n" .
        "开始时间:%snn" .
        "请登录后台查看生产任务安排。",
        'textdomain'),
        $product_title,
        date('Ymd'),
        $product_id,
        get_post_meta($product_id, '_preorder_sold', true),
        current_time('mysql')
    );
    
    wp_mail($admin_email, $subject, $message);
}

}

// 定期检查生产触发条件
add_action('init', function() {

if (!wp_next_scheduled('check_preorder_production')) {
    wp_schedule_event(time(), 'daily', 'check_preorder_production');
}

});

add_action('check_preorder_production', function() {

$args = array(
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'meta_query'     => array(
        array(
            'key'   => '_production_triggered',
            'compare' => 'NOT EXISTS'
        ),
        array(
            'key'   => '_preorder_goal',
            'compare' => 'EXISTS'
        )
    )
);

$products = get_posts($args);

foreach ($products as $product) {
    Production_Trigger::check_and_trigger_production($product->ID);
}

});


## 九、后台管理界面优化

### 9.1 预售产品管理面板

/**

  • 添加预售产品管理列
    */

function add_preorder_admin_columns($columns) {

$new_columns = array();

foreach ($columns as $key => $column) {
    $new_columns[$key] = $column;
    
    if ($key === 'product_type') {
        $new_columns['preorder_status'] = __('预售状态', 'textdomain');
        $new_columns['preorder_progress'] = __('达成进度', 'textdomain');
        $new_columns['production_status'] = __('生产状态', 'textdomain');
    }
}

return $new_columns;

}
add_filter('manage_product_posts_columns', 'add_preorder_admin_columns');

/**

  • 显示预售产品管理列内容
    */

function display_preorder_admin_columns($column, $product_id) {

$product = wc_get_product($product_id);

if ($product->get_type() !== 'preorder') {
    return;
}

switch ($column) {
    case 'preorder_status':
        $end_date = $product->get_preorder_end_date();
        if ($end_date) {
            if ($product->is_preorder_active()) {
                $days_left = ceil((strtotime($end_date) - current_time('timestamp')) / DAY_IN_SECONDS);
                echo '<span style="color: #4CAF50;">';
                printf(__('进行中(剩%d天)', 'textdomain'), $days_left);
                echo '</span>';
            } else {
                echo '<span style="color: #ff5722;">' . __('已结束', 'textdomain') . '</span>';
            }
        }
        break;
        
    case 'preorder_progress':
        $goal = get_post_meta($product_id, '_preorder_goal', true);
        $sold = get_post_meta($product_id, '_preorder_sold', true) ?: 0;
        
        if ($goal) {
            $percentage = min(100, ($sold / $goal) * 100);
            echo '<div style="background: #f0f0f0; height: 20px; width: 100px; border-radius: 10px; overflow: hidden; display: inline-block; vertical-align: middle;">';
            echo '<div style="background: linear-gradient(90deg, #4CAF50, #8BC34A); height: 100%; width: ' . $percentage . '%;"></div>';
            echo '</div>';
            echo '<span style="margin-left: 10px;">' . round($percentage, 1) . '%</span>';
        }
        break;
        
    case 'production_status':
        $status = get_post_meta($product_id, '_production_status', true);
        $status_labels = array(
            'pending'     => array('label' => __('等待生产', 'textdomain'), 'color' => '#9e9e9e'),
            'designing'   => array('label' => __('设计中', 'textdomain'), 'color' => '#2196F3'),
            'producing'   => array('label' => __('生产中', 'textdomain'), 'color' => '#FF9800'),
            'completed'   => array('label' => __('已完成', 'textdomain'), 'color' => '#4CAF50')
        );
        
        if ($status && isset($status_labels[$status])) {
            echo '<span style="background: ' . $status_labels[$status]['color'] . '; color: white; padding: 2px 8px; border-radius: 3px; font-size: 12px;">';
            echo $status_labels[$status]['label'];
            echo '</span>';
        }
        break;
}

}
add_action('manage_product_posts_custom_column', 'display_preorder_admin_columns', 10, 2);

/**

  • 添加快速编辑选项
    */

function add_preorder_quick_edit($column_name, $post_type) {

if ($column_name !== 'preorder_status' || $post_type !== 'product') {
    return;
}
?>
<fieldset class="inline-edit-col-right">
    <div class="inline-edit-col">
        <label class="alignleft">
            <span class="title"><?php _e('预售结束日期', 'textdomain'); ?></span>
            <span class="input-text-wrap">
                <input type="date" name="_preorder_end_date" class="text" value="">
            </span>
        </label>
        <br class="clear">
        <label class="alignleft">
            <span class="title"><?php _e('预售目标', 'textdomain'); ?></span>
            <span class="input-text-wrap">
                <input type="number" name="_preorder_goal" class="text" value="" min="1">
            </span>
        </label>
    </div>
</fieldset>
<?php

}
add_action('quick_edit_custom_box', 'add_preorder_quick_edit', 10, 2);

/**

  • 保存快速编辑数据
    */

function save_preorder_quick_edit($product) {

if (isset($_REQUEST['_preorder_end_date'])) {
    update_post_meta($product->get_id(), '_preorder_end_date', sanitize_text_field($_REQUEST['_preorder_end_date']));
}

if (isset($_REQUEST['_preorder_goal'])) {
    update_post_meta($product->get_id(), '_preorder_goal', absint($_REQUEST['_preorder_goal']));
}

}
add_action('woocommerce_product_quick_edit_save', 'save_preorder_quick_edit');


## 十、数据报表与分析

### 10.1 预售数据统计

/**

  • 生成预售数据报表
    */

class Preorder_Analytics {


// 获取总体统计数据
public static function get_overall_stats() {
    global $wpdb;
    
    $stats = array(
        'total_preorder_products' => 0,
        'active_preorders' => 0,
        'total_preorder_amount' => 0,
        'total_preorder_items' => 0,
        'avg_goal_achievement' => 0
    );
    
    // 获取所有预售产品
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
        'meta_query
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5871.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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