WordPress小批量定制插件与MES系统对接的详细教程
概述
在当今数字化制造环境中,制造执行系统(MES)已成为工厂管理的核心。对于使用WordPress搭建企业网站或内部管理平台的公司来说,将WordPress与MES系统对接可以实现生产数据的实时展示、订单状态跟踪和库存管理等功能。本教程将详细介绍如何开发一个WordPress定制插件,实现与MES系统的API对接。
环境准备与插件基础结构
首先,我们需要创建一个基础的WordPress插件结构。在WordPress的wp-content/plugins目录下创建一个新文件夹,命名为mes-connector。
<?php
/**
* Plugin Name: MES系统对接插件
* Plugin URI: https://yourwebsite.com/
* Description: 用于连接WordPress与MES系统的定制插件
* Version: 1.0.0
* Author: 你的名字
* License: GPL v2 or later
* Text Domain: mes-connector
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('MES_CONNECTOR_VERSION', '1.0.0');
define('MES_CONNECTOR_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('MES_CONNECTOR_PLUGIN_URL', plugin_dir_url(__FILE__));
// 初始化插件
class MES_Connector_Init {
public function __construct() {
// 注册激活和停用钩子
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// 初始化插件功能
add_action('plugins_loaded', array($this, 'init'));
}
public function activate() {
// 创建必要的数据库表
$this->create_database_tables();
// 设置默认选项
$this->set_default_options();
// 刷新重写规则
flush_rewrite_rules();
}
public function deactivate() {
// 清理临时数据
$this->cleanup_temporary_data();
// 刷新重写规则
flush_rewrite_rules();
}
public function init() {
// 加载语言文件
load_plugin_textdomain('mes-connector', false, dirname(plugin_basename(__FILE__)) . '/languages');
// 加载核心类
$this->load_core_classes();
// 注册短代码
$this->register_shortcodes();
// 添加管理菜单
if (is_admin()) {
add_action('admin_menu', array($this, 'add_admin_menu'));
}
}
private function create_database_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'mes_sync_log';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
sync_time datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
operation_type varchar(50) NOT NULL,
data_type varchar(50) NOT NULL,
status varchar(20) NOT NULL,
message text,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
private function set_default_options() {
// 设置默认的MES API配置
$default_options = array(
'mes_api_url' => 'https://mes.yourcompany.com/api/v1',
'api_timeout' => 30,
'sync_interval' => 300, // 5分钟
'enable_logging' => true
);
foreach ($default_options as $key => $value) {
if (get_option($key) === false) {
update_option($key, $value);
}
}
}
private function cleanup_temporary_data() {
// 清理插件生成的临时数据
// 这里可以根据需要添加清理逻辑
}
private function load_core_classes() {
// 加载核心功能类
require_once MES_CONNECTOR_PLUGIN_DIR . 'includes/class-mes-api-client.php';
require_once MES_CONNECTOR_PLUGIN_DIR . 'includes/class-mes-data-processor.php';
require_once MES_CONNECTOR_PLUGIN_DIR . 'includes/class-mes-sync-manager.php';
}
private function register_shortcodes() {
// 注册短代码
add_shortcode('mes_production_status', array($this, 'production_status_shortcode'));
add_shortcode('mes_order_tracking', array($this, 'order_tracking_shortcode'));
}
public function add_admin_menu() {
// 添加管理菜单
add_menu_page(
'MES系统设置',
'MES对接',
'manage_options',
'mes-connector',
array($this, 'admin_settings_page'),
'dashicons-admin-generic',
30
);
add_submenu_page(
'mes-connector',
'API设置',
'API设置',
'manage_options',
'mes-api-settings',
array($this, 'api_settings_page')
);
add_submenu_page(
'mes-connector',
'同步日志',
'同步日志',
'manage_options',
'mes-sync-logs',
array($this, 'sync_logs_page')
);
}
public function admin_settings_page() {
// 主设置页面内容
include MES_CONNECTOR_PLUGIN_DIR . 'admin/views/settings-page.php';
}
public function api_settings_page() {
// API设置页面内容
include MES_CONNECTOR_PLUGIN_DIR . 'admin/views/api-settings-page.php';
}
public function sync_logs_page() {
// 同步日志页面内容
include MES_CONNECTOR_PLUGIN_DIR . 'admin/views/sync-logs-page.php';
}
public function production_status_shortcode($atts) {
// 生产状态短代码处理
$atts = shortcode_atts(array(
'order_id' => '',
'limit' => 5
), $atts, 'mes_production_status');
ob_start();
include MES_CONNECTOR_PLUGIN_DIR . 'public/views/production-status.php';
return ob_get_clean();
}
public function order_tracking_shortcode($atts) {
// 订单跟踪短代码处理
$atts = shortcode_atts(array(
'order_number' => ''
), $atts, 'mes_order_tracking');
ob_start();
include MES_CONNECTOR_PLUGIN_DIR . 'public/views/order-tracking.php';
return ob_get_clean();
}
}
// 初始化插件
new MES_Connector_Init();
?>
MES API客户端类实现
接下来,我们创建MES API客户端类,负责与MES系统进行通信。
<?php
/**
* MES API客户端类
* 处理与MES系统的API通信
*/
class MES_API_Client {
private $api_url;
private $api_key;
private $timeout;
public function __construct() {
// 从WordPress选项获取API配置
$this->api_url = get_option('mes_api_url', '');
$this->api_key = get_option('mes_api_key', '');
$this->timeout = get_option('api_timeout', 30);
}
/**
* 发送GET请求到MES API
* @param string $endpoint API端点
* @param array $params 查询参数
* @return array|WP_Error 响应数据或错误
*/
public function get($endpoint, $params = array()) {
$url = $this->build_url($endpoint, $params);
$args = array(
'timeout' => $this->timeout,
'headers' => $this->get_headers()
);
$response = wp_remote_get($url, $args);
return $this->handle_response($response);
}
/**
* 发送POST请求到MES API
* @param string $endpoint API端点
* @param array $data 发送的数据
* @return array|WP_Error 响应数据或错误
*/
public function post($endpoint, $data = array()) {
$url = $this->build_url($endpoint);
$args = array(
'method' => 'POST',
'timeout' => $this->timeout,
'headers' => $this->get_headers(),
'body' => json_encode($data)
);
$response = wp_remote_post($url, $args);
return $this->handle_response($response);
}
/**
* 构建完整的API URL
* @param string $endpoint API端点
* @param array $params 查询参数
* @return string 完整的URL
*/
private function build_url($endpoint, $params = array()) {
$url = trailingslashit($this->api_url) . $endpoint;
if (!empty($params)) {
$url = add_query_arg($params, $url);
}
return $url;
}
/**
* 获取API请求头
* @return array 请求头数组
*/
private function get_headers() {
$headers = array(
'Content-Type' => 'application/json',
'Accept' => 'application/json'
);
if (!empty($this->api_key)) {
$headers['Authorization'] = 'Bearer ' . $this->api_key;
}
return $headers;
}
/**
* 处理API响应
* @param array|WP_Error $response WordPress响应对象
* @return array|WP_Error 处理后的响应
*/
private function handle_response($response) {
// 记录API调用日志
$this->log_api_call($response);
// 检查是否发生错误
if (is_wp_error($response)) {
return $response;
}
$response_code = wp_remote_retrieve_response_code($response);
$response_body = wp_remote_retrieve_body($response);
// 解析JSON响应
$data = json_decode($response_body, true);
// 检查HTTP状态码
if ($response_code >= 400) {
$error_message = isset($data['message']) ? $data['message'] : 'API请求失败';
return new WP_Error('api_error', $error_message, array('status' => $response_code));
}
return array(
'success' => true,
'data' => $data,
'code' => $response_code
);
}
/**
* 记录API调用日志
* @param array|WP_Error $response 响应对象
*/
private function log_api_call($response) {
if (!get_option('enable_logging', true)) {
return;
}
global $wpdb;
$table_name = $wpdb->prefix . 'mes_sync_log';
$log_data = array(
'operation_type' => 'api_call',
'data_type' => 'request',
'status' => is_wp_error($response) ? 'error' : 'success',
'message' => is_wp_error($response) ? $response->get_error_message() : 'API调用完成'
);
$wpdb->insert($table_name, $log_data);
}
/**
* 获取生产订单状态
* @param string $order_id 订单ID
* @return array 订单状态数据
*/
public function get_production_order_status($order_id) {
$endpoint = 'production/orders/' . $order_id . '/status';
return $this->get($endpoint);
}
/**
* 获取生产进度数据
* @param array $filters 过滤条件
* @return array 生产进度数据
*/
public function get_production_progress($filters = array()) {
$endpoint = 'production/progress';
return $this->get($endpoint, $filters);
}
/**
* 同步生产数据到WordPress
* @param array $data 生产数据
* @return array 同步结果
*/
public function sync_production_data($data) {
$endpoint = 'production/sync';
return $this->post($endpoint, $data);
}
/**
* 获取库存信息
* @param string $material_id 物料ID
* @return array 库存数据
*/
public function get_inventory($material_id = '') {
$endpoint = 'inventory';
$params = array();
if (!empty($material_id)) {
$params['material_id'] = $material_id;
}
return $this->get($endpoint, $params);
}
}
?>
数据同步管理器
创建数据同步管理器,负责定期从MES系统同步数据到WordPress。
<?php
/**
* MES数据同步管理器
* 处理定时同步任务和数据缓存
*/
class MES_Sync_Manager {
private $api_client;
private $data_processor;
public function __construct() {
$this->api_client = new MES_API_Client();
$this->data_processor = new MES_Data_Processor();
// 注册定时任务
add_action('mes_sync_cron_job', array($this, 'sync_data'));
// 初始化定时任务
$this->init_cron_job();
}
/**
* 初始化定时任务
*/
private function init_cron_job() {
if (!wp_next_scheduled('mes_sync_cron_job')) {
$interval = get_option('sync_interval', 300);
wp_schedule_event(time(), $this->get_cron_schedule($interval), 'mes_sync_cron_job');
}
}
/**
* 根据间隔获取cron计划
* @param int $interval 同步间隔(秒)
* @return string cron计划名称
*/
private function get_cron_schedule($interval) {
// 将秒转换为WordPress cron计划
if ($interval <= 300) { // 5分钟
return 'five_minutes';
} elseif ($interval <= 900) { // 15分钟
return 'fifteen_minutes';
} else {
return 'hourly';
}
}
/**
* 执行数据同步
*/
public function sync_data() {
$this->log_sync_start();
try {
// 同步生产订单数据
$this->sync_production_orders();
// 同步库存数据
$this->sync_inventory_data();
// 同步生产进度数据
$this->sync_production_progress();
$this->log_sync_complete();
} catch (Exception $e) {
$this->log_sync_error($e->getMessage());
}
}
/**
* 同步生产订单数据
*/
private function sync_production_orders() {
// 获取需要同步的订单ID列表
$orders_to_sync = $this->get_orders_to_sync();
foreach ($orders_to_sync as $order_id) {
$response = $this->api_client->get_production_order_status($order_id);
if ($response['success']) {
$this->data_processor->process_order_data($response['data']);
$this->log_sync_operation('order_sync', 'success', "订单 {$order_id} 同步成功");
} else {
$this->log_sync_operation('order_sync', 'error', "订单 {$order_id} 同步失败");
}
// 避免API速率限制,添加短暂延迟
sleep(1);
}
}
/**
* 同步库存数据
*/
private function sync_inventory_data() {
$response = $this->api_client->get_inventory();
if ($response['success']) {
$this->data_processor->process_inventory_data($response['data']);
$this->log_sync_operation('inventory_sync', 'success', '库存数据同步成功');
} else {
$this->log_sync_operation('inventory_sync', 'error', '库存数据同步失败');
}
}
/**
* 同步生产进度数据
*/
private function sync_production_progress() {
$filters = array(
'date_from' => date('Y-m-d', strtotime('-7 days')),
'date_to' => date('Y-m-d')
);
$response = $this->api_client->get_production_progress($filters);
if ($response['success']) {
$this->data_processor->process_progress_data($response['data']);
$this->log_sync_operation('progress_sync', 'success', '生产进度数据同步成功');
} else {
$this->log_sync_operation('progress_sync', 'error', '生产进度数据同步失败');
}
}
/**
* 获取需要同步的订单列表
* @return array 订单ID数组
*/
private function get_orders_to_sync() {
// 这里可以从WordPress数据库获取需要同步的订单
// 示例:返回最近7天内的订单
global $wpdb;
$query = "SELECT DISTINCT order_id FROM {$wpdb->prefix}mes_orders
WHERE sync_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)
OR sync_date IS NULL
LIMIT 50";
$results = $wpdb->get_results($query, ARRAY_A);
$order_ids = array();
foreach ($results as $row) {
$order_ids[] = $row['order_id'];
}
return $order_ids;
}
/**
* 记录同步开始
*/
private function log_sync_start() {
$this->log_sync_operation('sync_start', 'processing', '开始数据同步');
}
/**
* 记录同步完成
*/
private function log_sync_complete() {
$this->log_sync_operation('sync_complete', 'success', '数据同步完成');
}
/**
* 记录同步错误
* @param string $error_message 错误信息
*/
private function log_sync_error($error_message) {
$this->log_sync_operation('sync_error', 'error', $error_message);
}
/**
* 记录同步操作
* @param string $operation_type 操作类型
* @param string $status 状态
* @param string $message 消息
*/
private function log_sync_operation($operation_type, $status, $message) {
if (!get_option('enable_logging', true)) {
return;
}
global $wpdb;
$table_name = $wpdb->prefix . 'mes_sync_log';
$log_data = array(
'operation_type' => $operation_type,
'data_type' => 'sync',
'status' => $status,
'message' => $message
);
$wpdb->insert($table_name, $log_data);
}
/**
* 手动触发数据同步
* @return array 同步结果
*/
public function manual_sync() {
$result = array(
'success' => true,
'operations' => array()
);
try {
// 执行同步
$this->sync_data();
$result['operations'][] = array(
'type' => 'manual_sync',
'status' => 'success',
'message' => '手动同步完成'
);
} catch (Exception $e) {
$result['success'] = false;
$result['operations'][] = array(
'type' => 'manual_sync',
'status' => 'error',
'message' => $e->getMessage()
);
}
return $result;
}
}
?>
## 数据处理器类
创建数据处理器类,负责处理从MES系统获取的数据并存储到WordPress中。
<?php
/**
- MES数据处理器类
- 处理MES系统返回的数据并存储到WordPress
*/
class MES_Data_Processor {
/**
* 处理订单数据
* @param array $order_data 订单数据
*/
public function process_order_data($order_data) {
global $wpdb;
$table_name = $wpdb->prefix . 'mes_orders';
// 检查订单是否已存在
$existing_order = $wpdb->get_row(
$wpdb->prepare(
"SELECT id FROM $table_name WHERE order_id = %s",
$order_data['order_id']
)
);
$data = array(
'order_id' => sanitize_text_field($order_data['order_id']),
'customer_name' => sanitize_text_field($order_data['customer_name']),
'product_code' => sanitize_text_field($order_data['product_code']),
'quantity' => intval($order_data['quantity']),
'status' => sanitize_text_field($order_data['status']),
'start_date' => $this->parse_date($order_data['start_date']),
'estimated_completion' => $this->parse_date($order_data['estimated_completion']),
'actual_completion' => $this->parse_date($order_data['actual_completion']),
'sync_date' => current_time('mysql')
);
if ($existing_order) {
// 更新现有订单
$wpdb->update($table_name, $data, array('id' => $existing_order->id));
} else {
// 插入新订单
$wpdb->insert($table_name, $data);
}
// 创建或更新WordPress自定义文章类型
$this->create_order_post($order_data);
}
/**
* 处理库存数据
* @param array $inventory_data 库存数据
*/
public function process_inventory_data($inventory_data) {
global $wpdb;
$table_name = $wpdb->prefix . 'mes_inventory';
foreach ($inventory_data as $item) {
// 检查库存项是否已存在
$existing_item = $wpdb->get_row(
$wpdb->prepare(
"SELECT id FROM $table_name WHERE material_id = %s",
$item['material_id']
)
);
$data = array(
'material_id' => sanitize_text_field($item['material_id']),
'material_name' => sanitize_text_field($item['material_name']),
'category' => sanitize_text_field($item['category']),
'current_stock' => intval($item['current_stock']),
'minimum_stock' => intval($item['minimum_stock']),
'unit' => sanitize_text_field($item['unit']),
'last_updated' => current_time('mysql')
);
if ($existing_item) {
// 更新现有库存项
$wpdb->update($table_name, $data, array('id' => $existing_item->id));
} else {
// 插入新库存项
$wpdb->insert($table_name, $data);
}
}
}
/**
* 处理生产进度数据
* @param array $progress_data 生产进度数据
*/
public function process_progress_data($progress_data) {
global $wpdb;
$table_name = $wpdb->prefix . 'mes_production_progress';
foreach ($progress_data as $progress) {
// 检查进度记录是否已存在
$existing_progress = $wpdb->get_row(
$wpdb->prepare(
"SELECT id FROM $table_name WHERE order_id = %s AND workstation_id = %s AND operation_date = %s",
$progress['order_id'],
$progress['workstation_id'],
$this->parse_date($progress['operation_date'])
)
);
$data = array(
'order_id' => sanitize_text_field($progress['order_id']),
'workstation_id' => sanitize_text_field($progress['workstation_id']),
'workstation_name' => sanitize_text_field($progress['workstation_name']),
'operation' => sanitize_text_field($progress['operation']),
'operator' => sanitize_text_field($progress['operator']),
'quantity_completed' => intval($progress['quantity_completed']),
'quantity_defective' => intval($progress['quantity_defective']),
'operation_date' => $this->parse_date($progress['operation_date']),
'duration_minutes' => intval($progress['duration_minutes']),
'sync_date' => current_time('mysql')
);
if ($existing_progress) {
// 更新现有进度记录
$wpdb->update($table_name, $data, array('id' => $existing_progress->id));
} else {
// 插入新进度记录
$wpdb->insert($table_name, $data);
}
}
}
/**
* 创建订单自定义文章
* @param array $order_data 订单数据
* @return int|WP_Error 文章ID或错误
*/
private function create_order_post($order_data) {
// 检查是否已存在对应的文章
$existing_posts = get_posts(array(
'post_type' => 'mes_order',
'meta_key' => 'order_id',
'meta_value' => $order_data['order_id'],
'posts_per_page' => 1
));
$post_data = array(
'post_title' => '订单 ' . $order_data['order_id'],
'post_content' => $this->generate_order_content($order_data),
'post_type' => 'mes_order',
'post_status' => 'publish',
'meta_input' => array(
'order_id' => $order_data['order_id'],
'customer_name' => $order_data['customer_name'],
'product_code' => $order_data['product_code'],
'quantity' => $order_data['quantity'],
'status' => $order_data['status'],
'start_date' => $order_data['start_date'],
'estimated_completion' => $order_data['estimated_completion'],
'actual_completion' => $order_data['actual_completion']
)
);
if (!empty($existing_posts)) {
// 更新现有文章
$post_data['ID'] = $existing_posts[0]->ID;
return wp_update_post($post_data);
} else {
// 创建新文章
return wp_insert_post($post_data);
}
}
/**
* 生成订单文章内容
* @param array $order_data 订单数据
* @return string 文章内容
*/
private function generate_order_content($order_data) {
$content = '<div class="mes-order-details">';
$content .= '<h3>订单详情</h3>';
$content .= '<table class="mes-order-table">';
$content .= '<tr><th>订单号</th><td>' . esc_html($order_data['order_id']) . '</td></tr>';
$content .= '<tr><th>客户名称</th><td>' . esc_html($order_data['customer_name']) . '</td></tr>';
$content .= '<tr><th>产品代码</th><td>' . esc_html($order_data['product_code']) . '</td></tr>';
$content .= '<tr><th>数量</th><td>' . esc_html($order_data['quantity']) . '</td></tr>';
$content .= '<tr><th>状态</th><td><span class="order-status status-' . esc_attr($order_data['status']) . '">' . esc_html($this->get_status_text($order_data['status'])) . '</span></td></tr>';
$content .= '<tr><th>开始日期</th><td>' . esc_html($order_data['start_date']) . '</td></tr>';
$content .= '<tr><th>预计完成</th><td>' . esc_html($order_data['estimated_completion']) . '</td></tr>';
if (!empty($order_data['actual_completion'])) {
$content .= '<tr><th>实际完成</th><td>' . esc_html($order_data['actual_completion']) . '</td></tr>';
}
$content .= '</table>';
$content .= '</div>';
return $content;
}
/**
* 获取状态文本
* @param string $status_code 状态代码
* @return string 状态文本
*/
private function get_status_text($status_code) {
$status_map = array(
'pending' => '待处理',
'processing' => '生产中',
'completed' => '已完成',
'cancelled' => '已取消',
'on_hold' => '暂停'
);
return isset($status_map[$status_code]) ? $status_map[$status_code] : $status_code;
}
/**
* 解析日期字符串
* @param string $date_string 日期字符串
* @return string 格式化后的日期
*/
private function parse_date($date_string) {
if (empty($date_string)) {
return null;
}
try {
$date = new DateTime($date_string);
return $date->format('Y-m-d H:i:s');
} catch (Exception $e) {
return null;
}
}
}
?>
## 前端展示模板
创建前端展示模板,用于在WordPress前端显示MES数据。
<?php
/**
- 生产状态展示模板
- 文件路径: public/views/production-status.php
*/
// 获取短代码属性
$order_id = !empty($atts['order_id']) ? $atts['order_id'] : '';
$limit = intval($atts['limit']);
// 获取生产状态数据
global $wpdb;
$table_name = $wpdb->prefix . 'mes_orders';
if (!empty($order_id)) {
// 显示特定订单的状态
$query = $wpdb->prepare(
"SELECT * FROM $table_name WHERE order_id = %s ORDER BY sync_date DESC LIMIT 1",
$order_id
);
$orders = $wpdb->get_results($query);
} else {
// 显示最新的订单状态
$query = $wpdb->prepare(
"SELECT * FROM $table_name ORDER BY sync_date DESC LIMIT %d",
$limit
);
$orders = $wpdb->get_results($query);
}
if (empty($orders)): ?>
<div class="mes-no-data">
<p>暂无生产订单数据</p>
</div>
<?php else: ?>
<div class="mes-production-status">
<h3>生产订单状态</h3>
<div class="mes-orders-list">
<?php foreach ($orders as $order): ?>
<div class="mes-order-item">
<div class="order-header">
<span class="order-id">订单号: <?php echo esc_html($order->order_id); ?></span>
<span class="order-status status-<?php echo esc_attr($order->status); ?>">
<?php
$status_text = array(
'pending' => '待处理',
'processing' => '生产中',
'completed' => '已完成',
'cancelled' => '已取消'
);
echo isset($status_text[$order->status]) ? $status_text[$order->status] : $order->status;
?>
</span>
</div>
<div class="order-details">
<p><strong>客户:</strong> <?php echo esc_html($order->customer_name); ?></p>
<p><strong>产品:</strong> <?php echo esc_html($order->product_code); ?></p>
<p><strong>数量:</strong> <?php echo esc_html($order->quantity); ?></p>
<p><strong>开始日期:</strong> <?php echo esc_html($order->start_date); ?></p>
<?php if ($order->estimated_completion): ?>
<p><strong>预计完成:</strong> <?php echo esc_html($order->estimated_completion); ?></p>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
<style>
.mes-production-status {
background: #f9f9f9;
border: 1px solid #ddd;
border-radius: 5px;
padding: 20px;
margin: 20px 0;
}
.mes-orders-list {
display: grid;
gap: 15px;
}
.mes-order-item {
background: white;
border: 1px solid #eee;
border-radius: 3px;
padding: 15px;
}
.order-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
padding-bottom: 10px;
border-bottom: 1px solid #eee;
}
.order-status {
padding: 3px 8px;
border-radius: 3px;
font-size: 12px;
font-weight: bold;
}
.status-pending {
background: #ffd700;
color: #333;
}
.status-processing {
background: #4CAF50;
color: white;
}
.status-completed {
background: #2196F3;
color: white;
}
.status-cancelled {
background: #f44336;
color: white;
}
.order-details p {
margin: 5px 0;
font-size: 14px;
}
.mes-no-data {
text-align: center;
padding: 20px;
color: #666;
}
</style>
## 管理设置页面
创建管理设置页面,用于配置插件选项。
<?php
/**
- API设置页面
- 文件路径: admin/views/api-settings-page.php
*/
// 检查用户权限
if (!current_user_can('manage_options')) {
wp_die('您没有权限访问此页面');
}
// 处理表单提交
if (isset($_POST['submit'])) {
// 验证nonce
check_admin_referer('mes_api_settings');
// 保存设置
update_option('mes_api_url', sanitize_text_field($_POST['mes_api_url']));
update_option('mes_api_key', sanitize_text_field($_POST['mes_api_key']));
update_option('api_timeout', intval($_POST['api_timeout']));
update_option('sync_interval', intval($_POST['sync_interval']));
update_option('enable_logging', isset($_POST['enable_logging']) ? true : false);
echo '<div class="notice notice-success"><p>设置已保存!</p></div>';
}
// 获取当前设置
$current_settings = array(
'mes_api_url' => get_option('mes_api_url'),
'mes_api_key' => get_option('mes_api_key'),
'api_timeout' => get_option('api_timeout', 30),
'sync_interval' => get_option('sync_interval', 300),
'enable_logging' => get_option('enable_logging', true)
);
?>
<div class="wrap">
<h1>MES API设置</h1>
<form method="post" action="">
<?php wp_nonce_field('mes_api_settings'); ?>
<table class="form-table">
<tr>
<th scope="row">
<label for="mes_api_url">MES API地址</label>
</th>
<td>
<input type="url" id="mes_api_url" name="mes_api_url"
value="<?php echo esc_attr($current_settings['mes_api_url']); ?
