首页 / 教程文章 / 小批量生产流程的WordPress插件集成开发教程

小批量生产流程的WordPress插件集成开发教程

小批量生产流程的WordPress插件集成开发教程

概述

在当今数字化生产环境中,小批量生产流程的高效管理对企业至关重要。本教程将指导您如何开发一个WordPress插件,将小批量生产流程集成到您的网站中,实现生产状态跟踪、订单管理和流程自动化。

环境准备与插件基础结构

首先,我们需要创建插件的基本文件结构。在WordPress的wp-content/plugins目录下创建一个新文件夹,命名为small-batch-production

<?php
/**
 * 插件名称: Small Batch Production Manager
 * 插件URI: https://yourwebsite.com/
 * 描述: 小批量生产流程管理插件
 * 版本: 1.0.0
 * 作者: Your Name
 * 作者URI: https://yourwebsite.com/
 * 许可证: GPL v2 or later
 * 文本域: small-batch-production
 */

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

// 定义插件常量
define('SBP_VERSION', '1.0.0');
define('SBP_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SBP_PLUGIN_URL', plugin_dir_url(__FILE__));

// 初始化插件
class SmallBatchProduction {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->init_hooks();
    }
    
    // 初始化钩子和动作
    private function init_hooks() {
        // 激活和停用钩子
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
        
        // 管理菜单
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // 加载文本域
        add_action('init', array($this, 'load_textdomain'));
        
        // 注册自定义帖子类型
        add_action('init', array($this, 'register_production_post_type'));
        
        // 注册短代码
        add_shortcode('production_status', array($this, 'production_status_shortcode'));
    }
    
    // 插件激活时执行
    public function activate() {
        $this->create_database_tables();
        flush_rewrite_rules();
    }
    
    // 插件停用时执行
    public function deactivate() {
        flush_rewrite_rules();
    }
    
    // 加载文本域
    public function load_textdomain() {
        load_plugin_textdomain(
            'small-batch-production',
            false,
            dirname(plugin_basename(__FILE__)) . '/languages'
        );
    }
    
    // 更多方法将在下面实现...
}

// 初始化插件
SmallBatchProduction::get_instance();
?>

数据库设计与表创建

小批量生产管理需要存储生产订单、流程步骤和状态信息。我们将创建必要的数据库表。

// 在SmallBatchProduction类中添加以下方法

/**
 * 创建插件所需的数据库表
 */
private function create_database_tables() {
    global $wpdb;
    
    $charset_collate = $wpdb->get_charset_collate();
    $table_name = $wpdb->prefix . 'sbp_production_orders';
    
    // 生产订单表
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        order_number varchar(100) NOT NULL,
        product_name varchar(255) NOT NULL,
        quantity int NOT NULL,
        customer_id mediumint(9),
        status varchar(50) DEFAULT 'pending',
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY order_number (order_number)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 生产流程步骤表
    $table_name = $wpdb->prefix . 'sbp_production_steps';
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        order_id mediumint(9) NOT NULL,
        step_name varchar(255) NOT NULL,
        step_description text,
        assigned_to mediumint(9),
        status varchar(50) DEFAULT 'pending',
        start_date datetime,
        completion_date datetime,
        estimated_hours decimal(5,2),
        actual_hours decimal(5,2),
        notes text,
        PRIMARY KEY (id),
        FOREIGN KEY (order_id) REFERENCES {$wpdb->prefix}sbp_production_orders(id) ON DELETE CASCADE
    ) $charset_collate;";
    
    dbDelta($sql);
}

自定义帖子类型与元数据

为了在WordPress后台管理生产订单,我们需要注册自定义帖子类型。

// 在SmallBatchProduction类中添加以下方法

/**
 * 注册生产订单自定义帖子类型
 */
public function register_production_post_type() {
    $labels = array(
        'name'               => __('生产订单', 'small-batch-production'),
        'singular_name'      => __('生产订单', 'small-batch-production'),
        'menu_name'          => __('小批量生产', 'small-batch-production'),
        'add_new'            => __('添加新订单', 'small-batch-production'),
        'add_new_item'       => __('添加新生产订单', 'small-batch-production'),
        'edit_item'          => __('编辑生产订单', 'small-batch-production'),
        'new_item'           => __('新生产订单', 'small-batch-production'),
        'view_item'          => __('查看生产订单', 'small-batch-production'),
        'search_items'       => __('搜索生产订单', 'small-batch-production'),
        'not_found'          => __('未找到生产订单', 'small-batch-production'),
        'not_found_in_trash' => __('回收站中未找到生产订单', 'small-batch-production')
    );
    
    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'production-order'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 30,
        'menu_icon'          => 'dashicons-hammer',
        'supports'           => array('title', 'editor', 'custom-fields'),
        'show_in_rest'       => true
    );
    
    register_post_type('production_order', $args);
    
    // 注册订单状态分类法
    $this->register_order_status_taxonomy();
}

/**
 * 注册订单状态分类法
 */
private function register_order_status_taxonomy() {
    $labels = array(
        'name'              => __('订单状态', 'small-batch-production'),
        'singular_name'     => __('订单状态', 'small-batch-production'),
        'search_items'      => __('搜索状态', 'small-batch-production'),
        'all_items'         => __('所有状态', 'small-batch-production'),
        'parent_item'       => __('父状态', 'small-batch-production'),
        'parent_item_colon' => __('父状态:', 'small-batch-production'),
        'edit_item'         => __('编辑状态', 'small-batch-production'),
        'update_item'       => __('更新状态', 'small-batch-production'),
        'add_new_item'      => __('添加新状态', 'small-batch-production'),
        'new_item_name'     => __('新状态名称', 'small-batch-production'),
        'menu_name'         => __('订单状态', 'small-batch-production')
    );
    
    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'order-status'),
        'show_in_rest'      => true
    );
    
    register_taxonomy('order_status', array('production_order'), $args);
    
    // 添加默认状态
    $this->add_default_order_statuses();
}

/**
 * 添加默认订单状态
 */
private function add_default_order_statuses() {
    $default_statuses = array(
        'pending'     => __('待处理', 'small-batch-production'),
        'design'      => __('设计中', 'small-batch-production'),
        'material'    => __('采购材料', 'small-batch-production'),
        'production'  => __('生产中', 'small-batch-production'),
        'quality'     => __('质量检查', 'small-batch-production'),
        'packaging'   => __('包装', 'small-batch-production'),
        'shipping'    => __('发货中', 'small-batch-production'),
        'completed'   => __('已完成', 'small-batch-production'),
        'cancelled'   => __('已取消', 'small-batch-production')
    );
    
    foreach ($default_statuses as $slug => $name) {
        if (!term_exists($name, 'order_status')) {
            wp_insert_term($name, 'order_status', array('slug' => $slug));
        }
    }
}

管理界面与功能实现

现在,让我们创建插件管理界面,用于管理生产订单和流程。

// 在SmallBatchProduction类中添加以下方法

/**
 * 添加管理菜单
 */
public function add_admin_menu() {
    // 主菜单
    add_menu_page(
        __('小批量生产管理', 'small-batch-production'),
        __('小批量生产', 'small-batch-production'),
        'manage_options',
        'sbp-dashboard',
        array($this, 'render_dashboard_page'),
        'dashicons-hammer',
        30
    );
    
    // 子菜单
    add_submenu_page(
        'sbp-dashboard',
        __('生产订单', 'small-batch-production'),
        __('生产订单', 'small-batch-production'),
        'manage_options',
        'edit.php?post_type=production_order'
    );
    
    add_submenu_page(
        'sbp-dashboard',
        __('添加工序', 'small-batch-production'),
        __('添加工序', 'small-batch-production'),
        'manage_options',
        'sbp-production-steps',
        array($this, 'render_production_steps_page')
    );
    
    add_submenu_page(
        'sbp-dashboard',
        __('报表统计', 'small-batch-production'),
        __('报表统计', 'small-batch-production'),
        'manage_options',
        'sbp-reports',
        array($this, 'render_reports_page')
    );
    
    add_submenu_page(
        'sbp-dashboard',
        __('插件设置', 'small-batch-production'),
        __('设置', 'small-batch-production'),
        'manage_options',
        'sbp-settings',
        array($this, 'render_settings_page')
    );
}

/**
 * 渲染仪表板页面
 */
public function render_dashboard_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('您没有权限访问此页面。', 'small-batch-production'));
    }
    
    // 获取统计数据
    global $wpdb;
    $orders_table = $wpdb->prefix . 'sbp_production_orders';
    
    $total_orders = $wpdb->get_var("SELECT COUNT(*) FROM $orders_table");
    $pending_orders = $wpdb->get_var("SELECT COUNT(*) FROM $orders_table WHERE status = 'pending'");
    $in_production = $wpdb->get_var("SELECT COUNT(*) FROM $orders_table WHERE status = 'production'");
    $completed_orders = $wpdb->get_var("SELECT COUNT(*) FROM $orders_table WHERE status = 'completed'");
    
    ?>
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        
        <div class="sbp-dashboard-stats">
            <div class="sbp-stat-card">
                <h3><?php _e('总订单数', 'small-batch-production'); ?></h3>
                <p class="stat-number"><?php echo esc_html($total_orders); ?></p>
            </div>
            <div class="sbp-stat-card">
                <h3><?php _e('待处理订单', 'small-batch-production'); ?></h3>
                <p class="stat-number"><?php echo esc_html($pending_orders); ?></p>
            </div>
            <div class="sbp-stat-card">
                <h3><?php _e('生产中订单', 'small-batch-production'); ?></h3>
                <p class="stat-number"><?php echo esc_html($in_production); ?></p>
            </div>
            <div class="sbp-stat-card">
                <h3><?php _e('已完成订单', 'small-batch-production'); ?></h3>
                <p class="stat-number"><?php echo esc_html($completed_orders); ?></p>
            </div>
        </div>
        
        <div class="sbp-recent-orders">
            <h2><?php _e('最近订单', 'small-batch-production'); ?></h2>
            <?php $this->render_recent_orders_table(); ?>
        </div>
    </div>
    
    <style>
        .sbp-dashboard-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        .sbp-stat-card {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            text-align: center;
        }
        .sbp-stat-card .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #2271b1;
            margin: 10px 0 0;
        }
    </style>
    <?php
}

/**
 * 渲染最近订单表格
 */
private function render_recent_orders_table() {
    global $wpdb;
    $orders_table = $wpdb->prefix . 'sbp_production_orders';
    
    $orders = $wpdb->get_results(
        "SELECT * FROM $orders_table ORDER BY created_at DESC LIMIT 10"
    );
    
    if (empty($orders)) {
        echo '<p>' . __('暂无订单数据。', 'small-batch-production') . '</p>';
        return;
    }
    
    echo '<table class="wp-list-table widefat fixed striped">';
    echo '<thead><tr>';
    echo '<th>' . __('订单号', 'small-batch-production') . '</th>';
    echo '<th>' . __('产品名称', 'small-batch-production') . '</th>';
    echo '<th>' . __('数量', 'small-batch-production') . '</th>';
    echo '<th>' . __('状态', 'small-batch-production') . '</th>';
    echo '<th>' . __('创建时间', 'small-batch-production') . '</th>';
    echo '</tr></thead>';
    echo '<tbody>';
    
    foreach ($orders as $order) {
        $status_badge = '<span class="sbp-status-badge sbp-status-' . esc_attr($order->status) . '">' 
            . esc_html($this->get_status_label($order->status)) . '</span>';
        
        echo '<tr>';
        echo '<td>' . esc_html($order->order_number) . '</td>';
        echo '<td>' . esc_html($order->product_name) . '</td>';
        echo '<td>' . esc_html($order->quantity) . '</td>';
        echo '<td>' . $status_badge . '</td>';
        echo '<td>' . esc_html($order->created_at) . '</td>';
        echo '</tr>';
    }
    
    echo '</tbody></table>';
}

/**
 * 获取状态标签
 */
private function get_status_label($status) {
    $status_labels = array(
        'pending'     => __('待处理', 'small-batch-production'),
        'design'      => __('设计中', 'small-batch-production'),
        'material'    => __('采购材料', 'small-batch-production'),
        'production'  => __('生产中', 'small-batch-production'),
        'quality'     => __('质量检查', 'small-batch-production'),
        'packaging'   => __('包装', 'small-batch-production'),
        'shipping'    => __('发货中', 'small-batch-production'),
        'completed'   => __('已完成', 'small-batch-production'),
        'cancelled'   => __('已取消', 'small-batch-production')
    );
    
    return isset($status_labels[$status]) ? $status_labels[$status] : $status;
}

前端展示与短代码集成

为了让客户能够查看他们的订单状态,我们需要创建前端展示功能。

// 在SmallBatchProduction类中添加以下方法

/**
 * 生产状态短代码
 */
public function production_status_shortcode($atts) {
    // 解析短代码属性
    $atts = shortcode_atts(array(
        'order_id' => 0,
        'order_number' => '',
        'customer_email' => ''
    ), $atts, 'production_status');
    
    // 根据提供的参数查找订单
    $order = $this->get_order_by_identifier($atts);
    
    if (!$order) {
        return '<div class="sbp-order-status-not-found">' 
            . __('未找到相关订单信息。', 'small-batch-production') . '</div>';
    }
    
    // 获取订单的生产步骤
    $steps = $this->get_order_production_steps($order->id);
    
    ob_start();
    ?>
    <div class="sbp-order-status-container">
        <h3><?php _e('生产订单状态', 'small-batch-production'); ?></h3>
        
        <div class="sbp-order-info">
            <p><strong><?php _e('订单号:', 'small-batch-production'); ?></strong> 
            <?php echo esc_html($order->order_number); ?></p>
            <p><strong><?php _e('产品名称:', 'small-batch-production'); ?></strong> 
            <?php echo esc_html($order->product_name); ?></p>
            <p><strong><?php _e('数量:', 'small-batch-production'); ?></strong> 
            <?php echo esc_html($order->quantity); ?></p>
            <p><strong><?php _e('当前状态:', 'small-batch-production'); ?></strong> 
            <span class="sbp-status-badge sbp-status-<?php echo esc_attr($order->status); ?>">
                <?php echo esc_html($this->get_status_label($order->status)); ?>
            </span></p>
        </div>
        
        <div class="sbp-production-timeline">
            <h4><?php _e('生产流程进度', 'small-batch-production'); ?></h4>
            <?php if (!empty($steps)) : ?>
                <div class="sbp-timeline-steps">
                    <?php foreach ($steps as $step) : 
                        $step_class = 'sbp-timeline-step';
                        $step_class .= ' sbp-step-status-' . esc_attr($step->status);
                        if ($step->status === 'completed') {
                            $step_class .= ' sbp-step-completed';
                        } elseif ($step->status === 'in_progress') {
                            $step_class .= ' sbp-step-in-progress';
                        }
                    ?>
                    <div class="<?php echo $step_class; ?>">
                        <div class="sbp-step-icon"></div>
                        <div class="sbp-step-content">
                            <h5><?php echo esc_html($step->step_name); ?></h5>
                            <?php if (!empty($step->step_description)) : ?>
                                <p><?php echo esc_html($step->step_description); ?></p>
                            <?php endif; ?>
                            <div class="sbp-step-meta">
                                <?php if ($step->start_date) : ?>
                                    <span><?php _e('开始:', 'small-batch-production'); ?> 
                                    <?php echo esc_html($step->start_date); ?></span>
                                <?php endif; ?>
                                <?php if ($step->completion_date) : ?>
                                    <span><?php _e('完成:', 'small-batch-production'); ?> 
                                    <?php echo esc_html($step->completion_date); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php else : ?>
                <p><?php _e('暂无生产步骤信息。', 'small-batch-production'); ?></p>
            <?php endif; ?>
        </div>
    </div>
    
    <style>
        .sbp-order-status-container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .sbp-order-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .sbp-status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .sbp-status-pending { background: #ffc107; color: #000; }
        .sbp-status-production { background: #17a2b8; color: #fff; }
        .sbp-status-completed { background: #28a745; color: #fff; }
        .sbp-status-cancelled { background: #dc3545; color: #fff; }
        
        .sbp-production-timeline {
            margin-top: 30px;
        }
        .sbp-timeline-steps {
            position: relative;
            padding-left: 30px;
        }
        .sbp-timeline-steps::before {
            content: '';
            position: absolute;
            left: 15px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e9ecef;
        }
        .sbp-timeline-step {
            position: relative;
            margin-bottom: 20px;
            padding-bottom: 20px;
        }
        .sbp-step-icon {
            position: absolute;
            left: -30px;
            top: 0;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #6c757d;
            border: 3px solid #fff;
            box-shadow: 0 0 0 3px #e9ecef;
        }
        .sbp-step-completed .sbp-step-icon {
            background: #28a745;
        }
        .sbp-step-in-progress .sbp-step-icon {
            background: #17a2b8;
            animation: pulse 2s infinite;
        }
        .sbp-step-content {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            border-left: 4px solid #6c757d;
        }
        .sbp-step-completed .sbp-step-content {
            border-left-color: #28a745;
        }
        .sbp-step-in-progress .sbp-step-content {
            border-left-color: #17a2b8;
        }
        .sbp-step-meta {
            display: flex;
            gap: 15px;
            margin-top: 10px;
            font-size: 12px;
            color: #6c757d;
        }
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(23, 162, 184, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(23, 162, 184, 0); }
            100% { box-shadow: 0 0 0 0 rgba(23, 162, 184, 0); }
        }
    </style>
    <?php
    
    return ob_get_clean();
}

/**
 * 根据标识符获取订单
 */
private function get_order_by_identifier($atts) {
    global $wpdb;
    $orders_table = $wpdb->prefix . 'sbp_production_orders';
    
    if (!empty($atts['order_id'])) {
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $orders_table WHERE id = %d",
            intval($atts['order_id'])
        ));
    }
    
    if (!empty($atts['order_number'])) {
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $orders_table WHERE order_number = %s",
            sanitize_text_field($atts['order_number'])
        ));
    }
    
    return null;
}

/**
 * 获取订单的生产步骤
 */
private function get_order_production_steps($order_id) {
    global $wpdb;
    $steps_table = $wpdb->prefix . 'sbp_production_steps';
    
    return $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM $steps_table WHERE order_id = %d ORDER BY id ASC",
        intval($order_id)
    ));
}

REST API 集成

为了支持现代前端框架和移动应用,我们需要创建REST API端点。

// 在SmallBatchProduction类中添加以下方法

/**
 * 注册REST API路由
 */
public function register_rest_routes() {
    add_action('rest_api_init', function() {
        // 获取所有生产订单
        register_rest_route('sbp/v1', '/orders', array(
            'methods' => 'GET',
            'callback' => array($this, 'rest_get_orders'),
            'permission_callback' => array($this, 'rest_check_permissions'),
            'args' => array(
                'status' => array(
                    'required' => false,
                    'validate_callback' => function($param) {
                        return in_array($param, array(
                            'pending', 'production', 'completed', 'cancelled'
                        ));
                    }
                ),
                'per_page' => array(
                    'required' => false,
                    'default' => 10,
                    'validate_callback' => function($param) {
                        return is_numeric($param) && $param > 0 && $param <= 100;
                    }
                ),
                'page' => array(
                    'required' => false,
                    'default' => 1,
                    'validate_callback' => function($param) {
                        return is_numeric($param) && $param > 0;
                    }
                )
            )
        ));
        
        // 获取单个订单详情
        register_rest_route('sbp/v1', '/orders/(?P<id>d+)', array(
            'methods' => 'GET',
            'callback' => array($this, 'rest_get_order'),
            'permission_callback' => array($this, 'rest_check_permissions')
        ));
        
        // 创建新订单
        register_rest_route('sbp/v1', '/orders', array(
            'methods' => 'POST',
            'callback' => array($this, 'rest_create_order'),
            'permission_callback' => array($this, 'rest_check_permissions')
        ));
        
        // 更新订单状态
        register_rest_route('sbp/v1', '/orders/(?P<id>d+)/status', array(
            'methods' => 'PUT',
            'callback' => array($this, 'rest_update_order_status'),
            'permission_callback' => array($this, 'rest_check_permissions')
        ));
        
        // 获取订单的生产步骤
        register_rest_route('sbp/v1', '/orders/(?P<id>d+)/steps', array(
            'methods' => 'GET',
            'callback' => array($this, 'rest_get_order_steps'),
            'permission_callback' => array($this, 'rest_check_permissions')
        ));
    });
}

/**
 * REST API权限检查
 */
public function rest_check_permissions($request) {
    // 这里可以根据需要实现更复杂的权限检查
    // 例如:检查API密钥、用户角色等
    return current_user_can('manage_options') || 
           $this->validate_api_key($request);
}

/**
 * 验证API密钥
 */
private function validate_api_key($request) {
    $api_key = $request->get_header('X-SBP-API-Key');
    $stored_key = get_option('sbp_api_key', '');
    
    return !empty($api_key) && hash_equals($stored_key, $api_key);
}

/**
 * REST API:获取订单列表
 */
public function rest_get_orders($request) {
    global $wpdb;
    $orders_table = $wpdb->prefix . 'sbp_production_orders';
    
    $params = $request->get_params();
    $per_page = intval($params['per_page']);
    $page = intval($params['page']);
    $offset = ($page - 1) * $per_page;
    
    // 构建查询
    $where = array('1=1');
    $query_params = array();
    
    if (!empty($params['status'])) {
        $where[] = 'status = %s';
        $query_params[] = sanitize_text_field($params['status']);
    }
    
    $where_clause = implode(' AND ', $where);
    
    // 获取订单数据
    $query = "SELECT * FROM $orders_table WHERE $where_clause 
              ORDER BY created_at DESC LIMIT %d OFFSET %d";
    
    $query_params[] = $per_page;
    $query_params[] = $offset;
    
    $orders = $wpdb->get_results(
        $wpdb->prepare($query, $query_params)
    );
    
    // 获取总数
    $count_query = "SELECT COUNT(*) FROM $orders_table WHERE $where_clause";
    $total = $wpdb->get_var(
        $wpdb->prepare($count_query, array_slice($query_params, 0, -2))
    );
    
    // 格式化响应数据
    $formatted_orders = array();
    foreach ($orders as $order) {
        $formatted_orders[] = array(
            'id' => intval($order->id),
            'order_number' => $order->order_number,
            'product_name' => $order->product_name,
            'quantity' => intval($order->quantity),
            'status' => $order->status,
            'status_label' => $this->get_status_label($order->status),
            'created_at' => $order->created_at,
            'updated_at' => $order->updated_at
        );
    }
    
    return rest_ensure_response(array(
        'success' => true,
        'data' => $formatted_orders,
        'pagination' => array(
            'total' => intval($total),
            'per_page' => $per_page,
            'current_page' => $page,
            'total_pages' => ceil($total / $per_page)
        )
    ));
}

/**
 * REST API:获取单个订单
 */
public function rest_get_order($request) {
    $order_id = intval($request['id']);
    $order = $this->get_order_by_identifier(array('order_id' => $order_id));
    
    if (!$order) {
        return new WP_Error(
            'order_not_found',
            __('订单不存在', 'small-batch-production'),
            array('status' => 404)
        );
    }
    
    // 获取订单步骤
    $steps = $this->get_order_production_steps($order_id);
    
    $response_data = array(
        'id' => intval($order->id),
        'order_number' => $order->order_number,
        'product_name' => $order->product_name,
        'quantity' => intval($order->quantity),
        'customer_id' => intval($order->customer_id),
        'status' => $order->status,
        'status_label' => $this->get_status_label($order->status),
        'created_at' => $order->created_at,
        'updated_at' => $order->updated_at,
        'production_steps' => $steps
    );
    
    return rest_ensure_response(array(
        'success' => true,
        'data' => $response_data
    ));
}

插件设置页面

最后,让我们创建插件设置页面,允许用户配置插件选项。

// 在SmallBatchProduction类中添加以下方法

/**
 * 渲染设置页面
 */
public function render_settings_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('您没有权限访问此页面。', 'small-batch-production'));
    }
    
    // 保存设置
    if (isset($_POST['sbp_save_settings']) && check_admin_referer('sbp_settings_nonce')) {
        $this->save_settings($_POST);
        echo '<div class="notice notice-success"><p>' . 
             __('设置已保存。', 'small-batch-production') . '</p></div>';
    }
    
    // 生成API密钥
    if (isset($_POST['sbp_generate_api_key']) && check_admin_referer('sbp_settings_nonce')) {
        $api_key = bin2hex(random_bytes(32));
        update_option('sbp_api_key', $api_key);
        echo '<div class="notice notice-success"><p>' . 
             __('API密钥已生成。', 'small-batch-production') . '</p></div>';
    }
    
    $current_settings = $this->get_settings();
    ?>
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        
        <form method="post" action="">
            <?php wp_nonce_field('sbp_settings_nonce'); ?>
            
            <h2><?php _e('常规设置', 'small-batch-production'); ?></h2>
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="sbp_default_status"><?php _e('默认订单状态', 'small-batch-production'); ?></label>
                    </th>
                    <td>
                        <select name="sbp_default_status" id="sbp_default_status">
                            <?php foreach ($this->get_all_statuses() as $status => $label) : ?>
                                <option value="<?php echo esc_attr($status); ?>" 
                                    <?php selected($current_settings['default_status'], $status); ?>>
                                    <?php echo esc_html($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p class="description"><?php _e('新创建订单的默认状态。', 'small-batch-production'); ?></p>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="sbp_notification_email"><?php _e('通知邮箱', 'small-batch-production'); ?></label>
                    </th>
                    <td>
                        <input type="email" name="sbp_notification_email" id="sbp_notification_email" 
                               value="<?php echo esc_attr($current_settings['notification_email']); ?>" 
                               class="regular-text">
                        <p class="description"><?php _e('状态变更时发送通知的邮箱地址。', 'small-batch-production'); ?></p>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="sbp_enable_customer_notifications"><?php _e('客户通知', 'small-batch-production'); ?></label>
                    </th>
                    <td>
                        <label>
                            <input type="checkbox" name="sbp_enable_customer_notifications" id="sbp_enable_customer_notifications" 
                                   value="1" <?php checked($current_settings['enable_customer_notifications'], 1); ?>>
                            <?php _e('启用客户邮件通知', 'small-batch-production'); ?>
                        </label>
                        <p class="description"><?php _e('订单状态变更时自动通知客户。', 'small-batch-production'); ?></p>
                    </td>
                </tr>
            </table>
            
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5811.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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