文章目录[隐藏]
WordPress小批量定制插件与WMS系统集成开发详解
概述:为什么需要WordPress与WMS系统集成
在当今电子商务快速发展的时代,许多企业使用WordPress搭建在线商店,同时使用专业的仓库管理系统(WMS)来管理库存和物流。然而,这两个系统往往独立运行,导致数据不同步、操作繁琐等问题。通过开发定制插件实现WordPress与WMS系统的集成,可以实时同步库存数据、自动化订单处理流程,显著提高运营效率。
本教程将详细介绍如何开发一个小批量的WordPress定制插件,实现与WMS系统的API集成,包含完整的代码示例和详细注释。
开发环境准备与插件基础结构
首先,我们需要创建一个标准的WordPress插件结构。以下是插件的基础文件结构:
wms-integration/
├── wms-integration.php # 主插件文件
├── includes/
│ ├── class-api-handler.php # API处理类
│ ├── class-order-sync.php # 订单同步类
│ └── class-admin-settings.php # 后台设置类
├── assets/
│ ├── css/
│ └── js/
└── uninstall.php # 卸载脚本
主插件文件 (wms-integration.php):
<?php
/**
* Plugin Name: WMS系统集成插件
* Plugin URI: https://yourwebsite.com/
* Description: 实现WordPress与WMS系统的集成,同步库存和订单数据
* Version: 1.0.0
* Author: 开发者名称
* License: GPL v2 or later
* Text Domain: wms-integration
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('WMS_INTEGRATION_VERSION', '1.0.0');
define('WMS_INTEGRATION_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WMS_INTEGRATION_PLUGIN_URL', plugin_dir_url(__FILE__));
// 自动加载类文件
spl_autoload_register(function ($class_name) {
$prefix = 'WMS_Integration_';
$base_dir = WMS_INTEGRATION_PLUGIN_DIR . 'includes/';
// 检查类名是否使用我们的前缀
$len = strlen($prefix);
if (strncmp($prefix, $class_name, $len) !== 0) {
return;
}
$relative_class = substr($class_name, $len);
$file = $base_dir . 'class-' . strtolower(str_replace('_', '-', $relative_class)) . '.php';
if (file_exists($file)) {
require_once $file;
}
});
// 初始化插件
function wms_integration_init() {
// 检查WooCommerce是否激活(如果使用WooCommerce)
if (class_exists('WooCommerce')) {
$plugin = new WMS_Integration_Core();
$plugin->run();
} else {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>WMS集成插件需要WooCommerce支持,请先安装并激活WooCommerce插件。</p></div>';
});
}
}
add_action('plugins_loaded', 'wms_integration_init');
// 激活和停用钩子
register_activation_hook(__FILE__, 'wms_integration_activate');
register_deactivation_hook(__FILE__, 'wms_integration_deactivate');
function wms_integration_activate() {
// 创建必要的数据库表或选项
update_option('wms_integration_version', WMS_INTEGRATION_VERSION);
// 设置默认选项
$default_options = array(
'api_url' => '',
'api_key' => '',
'sync_interval' => 'hourly',
'auto_sync' => true,
);
add_option('wms_integration_settings', $default_options);
}
function wms_integration_deactivate() {
// 清理定时任务
wp_clear_scheduled_hook('wms_integration_sync_event');
}
WMS API连接处理类
接下来,我们创建API处理类,负责与WMS系统进行通信:
<?php
/**
* WMS API处理类
* 处理与WMS系统的API通信
*/
class WMS_Integration_API_Handler {
private $api_url;
private $api_key;
private $timeout = 30;
public function __construct($api_url, $api_key) {
$this->api_url = rtrim($api_url, '/');
$this->api_key = $api_key;
}
/**
* 发送GET请求到WMS API
* @param string $endpoint API端点
* @param array $params 查询参数
* @return array 响应数据
*/
public function get($endpoint, $params = array()) {
$url = $this->api_url . '/' . ltrim($endpoint, '/');
// 添加认证参数
$params['api_key'] = $this->api_key;
if (!empty($params)) {
$url .= '?' . http_build_query($params);
}
$args = array(
'timeout' => $this->timeout,
'headers' => array(
'Accept' => 'application/json',
),
);
$response = wp_remote_get($url, $args);
return $this->handle_response($response);
}
/**
* 发送POST请求到WMS API
* @param string $endpoint API端点
* @param array $data 发送的数据
* @return array 响应数据
*/
public function post($endpoint, $data = array()) {
$url = $this->api_url . '/' . ltrim($endpoint, '/');
$args = array(
'timeout' => $this->timeout,
'headers' => array(
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'X-API-Key' => $this->api_key,
),
'body' => wp_json_encode($data),
);
$response = wp_remote_post($url, $args);
return $this->handle_response($response);
}
/**
* 处理API响应
* @param array|WP_Error $response WordPress响应
* @return array 解析后的数据
*/
private function handle_response($response) {
// 检查请求是否出错
if (is_wp_error($response)) {
return array(
'success' => false,
'error' => $response->get_error_message(),
);
}
$response_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// 检查HTTP状态码
if ($response_code !== 200) {
return array(
'success' => false,
'error' => "API请求失败,状态码:{$response_code}",
'data' => $data,
);
}
// 检查JSON解析是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
return array(
'success' => false,
'error' => 'JSON解析失败: ' . json_last_error_msg(),
'raw_body' => $body,
);
}
return array(
'success' => true,
'data' => $data,
'response_code' => $response_code,
);
}
/**
* 测试API连接
* @return bool 连接是否成功
*/
public function test_connection() {
$result = $this->get('/api/test');
if ($result['success'] && isset($result['data']['status']) && $result['data']['status'] === 'ok') {
return true;
}
return false;
}
/**
* 获取库存信息
* @param string $sku 产品SKU
* @return array 库存数据
*/
public function get_stock($sku) {
$result = $this->get('/api/inventory', array('sku' => $sku));
if ($result['success'] && isset($result['data']['stock'])) {
return array(
'success' => true,
'stock' => $result['data']['stock'],
'sku' => $sku,
);
}
return array(
'success' => false,
'error' => $result['error'] ?? '获取库存信息失败',
'sku' => $sku,
);
}
/**
* 同步订单到WMS
* @param int $order_id WordPress订单ID
* @param array $order_data 订单数据
* @return array 同步结果
*/
public function sync_order($order_id, $order_data) {
$result = $this->post('/api/orders', $order_data);
if ($result['success'] && isset($result['data']['order_id'])) {
// 更新订单元数据,标记为已同步
update_post_meta($order_id, '_wms_synced', true);
update_post_meta($order_id, '_wms_sync_time', current_time('mysql'));
update_post_meta($order_id, '_wms_order_id', $result['data']['order_id']);
return array(
'success' => true,
'wms_order_id' => $result['data']['order_id'],
'message' => '订单同步成功',
);
}
return array(
'success' => false,
'error' => $result['error'] ?? '订单同步失败',
'order_id' => $order_id,
);
}
}
订单同步功能实现
现在,我们创建订单同步类,处理WordPress订单与WMS系统的同步:
<?php
/**
* 订单同步类
* 处理WordPress订单与WMS系统的同步逻辑
*/
class WMS_Integration_Order_Sync {
private $api_handler;
public function __construct($api_handler) {
$this->api_handler = $api_handler;
// 添加订单状态变更钩子
add_action('woocommerce_order_status_processing', array($this, 'sync_order_to_wms'), 10, 1);
add_action('woocommerce_order_status_completed', array($this, 'sync_order_to_wms'), 10, 1);
// 添加定时同步任务
add_action('wms_integration_sync_event', array($this, 'sync_pending_orders'));
}
/**
* 同步单个订单到WMS
* @param int $order_id 订单ID
*/
public function sync_order_to_wms($order_id) {
// 检查订单是否已经同步过
$already_synced = get_post_meta($order_id, '_wms_synced', true);
if ($already_synced) {
error_log("订单 {$order_id} 已经同步到WMS,跳过");
return;
}
// 获取订单对象
$order = wc_get_order($order_id);
if (!$order) {
error_log("无法获取订单 {$order_id}");
return;
}
// 准备订单数据
$order_data = $this->prepare_order_data($order);
// 发送到WMS
$result = $this->api_handler->sync_order($order_id, $order_data);
if ($result['success']) {
// 添加订单备注
$order->add_order_note(
sprintf('订单已同步到WMS系统,WMS订单号: %s', $result['wms_order_id'])
);
error_log("订单 {$order_id} 同步成功,WMS订单号: {$result['wms_order_id']}");
} else {
// 同步失败,记录错误
$order->add_order_note(
sprintf('同步到WMS失败: %s', $result['error'])
);
error_log("订单 {$order_id} 同步失败: {$result['error']}");
// 可以在这里添加重试逻辑或通知管理员
}
}
/**
* 准备订单数据
* @param WC_Order $order WooCommerce订单对象
* @return array 格式化后的订单数据
*/
private function prepare_order_data($order) {
$order_items = array();
// 处理订单商品
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
$order_items[] = array(
'sku' => $product->get_sku(),
'name' => $item->get_name(),
'quantity' => $item->get_quantity(),
'price' => $item->get_subtotal(),
'product_id' => $product->get_id(),
);
}
// 获取配送地址
$shipping_address = array(
'first_name' => $order->get_shipping_first_name(),
'last_name' => $order->get_shipping_last_name(),
'company' => $order->get_shipping_company(),
'address_1' => $order->get_shipping_address_1(),
'address_2' => $order->get_shipping_address_2(),
'city' => $order->get_shipping_city(),
'state' => $order->get_shipping_state(),
'postcode' => $order->get_shipping_postcode(),
'country' => $order->get_shipping_country(),
'phone' => $order->get_billing_phone(),
);
// 构建完整订单数据
$order_data = array(
'order_id' => $order->get_id(),
'order_number' => $order->get_order_number(),
'order_date' => $order->get_date_created()->date('Y-m-d H:i:s'),
'customer_id' => $order->get_customer_id(),
'customer_note' => $order->get_customer_note(),
'billing' => array(
'first_name' => $order->get_billing_first_name(),
'last_name' => $order->get_billing_last_name(),
'email' => $order->get_billing_email(),
'phone' => $order->get_billing_phone(),
),
'shipping' => $shipping_address,
'items' => $order_items,
'shipping_method' => $order->get_shipping_method(),
'payment_method' => $order->get_payment_method(),
'total' => $order->get_total(),
'currency' => $order->get_currency(),
);
return $order_data;
}
/**
* 同步所有待处理订单
* 用于定时任务或手动触发
*/
public function sync_pending_orders() {
// 查询所有未同步的订单
$args = array(
'post_type' => 'shop_order',
'post_status' => array('wc-processing', 'wc-completed'),
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_wms_synced',
'compare' => 'NOT EXISTS',
),
),
);
$orders = get_posts($args);
$synced_count = 0;
$failed_count = 0;
foreach ($orders as $order_post) {
$result = $this->sync_order_to_wms($order_post->ID);
if ($result['success'] ?? false) {
$synced_count++;
} else {
$failed_count++;
}
// 避免请求过于频繁,添加短暂延迟
usleep(500000); // 0.5秒
}
return array(
'synced' => $synced_count,
'failed' => $failed_count,
'total' => count($orders),
);
}
/**
* 手动触发订单同步(用于后台管理)
* @param array $order_ids 订单ID数组
* @return array 同步结果
*/
public function manual_sync_orders($order_ids) {
$results = array(
'success' => array(),
'failed' => array(),
);
foreach ($order_ids as $order_id) {
$result = $this->sync_order_to_wms($order_id);
if ($result['success']) {
$results['success'][] = $order_id;
} else {
$results['failed'][] = array(
'order_id' => $order_id,
'error' => $result['error'],
);
}
}
return $results;
}
}
后台管理界面开发
为了让用户能够配置插件,我们需要创建一个后台设置页面:
<?php
/**
* 后台设置类
* 创建插件设置页面和处理设置保存
*/
class WMS_Integration_Admin_Settings {
private $settings_group = 'wms_integration_settings_group';
private $settings_page = 'wms-integration-settings';
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_submenu_page(
'woocommerce',
'WMS系统集成设置',
'WMS集成',
'manage_options',
$this->settings_page,
array($this, 'render_settings_page')
);
}
/**
* 注册设置选项
*/
public function register_settings() {
register_setting(
$this->settings_group,
'wms_integration_settings',
array($this, 'sanitize_settings')
);
// 基础设置部分
add_settings_section(
'wms_integration_basic',
'基础设置',
array($this, 'render_basic_section'),
$this->settings_page
);
// API设置字段
add_settings_field(
'api_url',
'WMS API地址',
array($this, 'render_api_url_field'),
$this->settings_page,
'wms_integration_basic'
);
add_settings_field(
'api_key',
'API密钥',
array($this, 'render_api_key_field'),
$this->settings_page,
'wms_integration_basic'
);
// 同步设置部分
add_settings_section(
'wms_integration_sync',
'同步设置',
array($this, 'render_sync_section'),
$this->settings_page
);
add_settings_field(
'auto_sync',
'自动同步',
array($this, 'render_auto_sync_field'),
$this->settings_page,
'wms_integration_sync'
);
add_settings_field(
'sync_interval',
'同步频率',
array($this, 'render_sync_interval_field'),
$this->settings_page,
'wms_integration_sync'
);
}
/**
* 渲染设置页面
*/
public function render_settings_page() {
if (!current_user_can('manage_options')) {
wp_die('您没有权限访问此页面');
}
?>
<div class="wrap">
<h1>WMS系统集成设置</h1>
<form method="post" action="options.php">
<?php
settings_fields($this->settings_group);
do_settings_sections($this->settings_page);
submit_button('保存设置');
?>
</form>
<hr>
<div class="wms-tools">
<h2>工具</h2>
<div class="card">
<h3>测试连接</h3>
<p>测试与WMS系统的API连接是否正常。</p>
<button type="button" id="test-connection" class="button button-secondary">
测试连接
</button>
<div id="test-result" style="margin-top: 10px;"></div>
</div>
<div class="card">
<h3>手动同步订单</h3>
<p>手动同步未处理的订单到WMS系统。</p>
<button type="button" id="manual-sync" class="button button-secondary">
开始同步
</button>
<div id="sync-result" style="margin-top: 10px;"></div>
</div>
</div>
</div>
<?php
}
/**
* 渲染基础设置部分
*/
public function render_basic_section() {
echo '<p>配置WMS系统的API连接信息。</p>';
}
/**
* 渲染API地址字段
*/
public function render_api_url_field() {
$options = get_option('wms_integration_settings');
$value = isset($options['api_url']) ? esc_url($options['api_url']) : '';
echo '<input type="url" id="api_url" name="wms_integration_settings[api_url]"
value="' . $value . '" class="regular-text"
placeholder="https://api.wms-system.com/v1">';
echo '<p class="description">请输入完整的WMS API地址</p>';
}
/**
* 渲染API密钥字段
*/
public function render_api_key_field() {
$options = get_option('wms_integration_settings');
$value = isset($options['api_key']) ? esc_attr($options['api_key']) : '';
echo '<input type="password" id="api_key" name="wms_integration_settings[api_key]"
value="' . $value . '" class="regular-text">';
echo '<p class="description">WMS系统提供的API密钥</p>';
}
/**
* 渲染同步设置部分
*/
public function render_sync_section() {
echo '<p>配置订单同步的相关设置。</p>';
}
/**
* 渲染自动同步字段
*/
public function render_auto_sync_field() {
$options = get_option('wms_integration_settings');
$checked = isset($options['auto_sync']) && $options['auto_sync'] ? 'checked' : '';
echo '<label>';
echo '<input type="checkbox" id="auto_sync" name="wms_integration_settings[auto_sync]"
value="1" ' . $checked . '>';
echo ' 启用自动同步订单到WMS系统';
echo '</label>';
echo '<p class="description">启用后,新订单将自动同步到WMS系统</p>';
}
/**
* 渲染同步频率字段
*/
public function render_sync_interval_field() {
$options = get_option('wms_integration_settings');
$value = isset($options['sync_interval']) ? $options['sync_interval'] : 'hourly';
$intervals = array(
'hourly' => '每小时',
'twicedaily' => '每天两次',
'daily' => '每天',
'weekly' => '每周',
);
echo '<select id="sync_interval" name="wms_integration_settings[sync_interval]">';
foreach ($intervals as $key => $label) {
$selected = ($value === $key) ? 'selected' : '';
echo '<option value="' . esc_attr($key) . '" ' . $selected . '>' . esc_html($label) . '</option>';
}
echo '</select>';
echo '<p class="description">定时同步未处理订单的频率</p>';
}
/**
* 清理和验证设置数据
*/
public function sanitize_settings($input) {
$sanitized = array();
// 清理API URL
if (isset($input['api_url'])) {
$sanitized['api_url'] = esc_url_raw(trim($input['api_url']));
}
// 清理API密钥
if (isset($input['api_key'])) {
$sanitized['api_key'] = sanitize_text_field(trim($input['api_key']));
}
// 处理自动同步选项
$sanitized['auto_sync'] = isset($input['auto_sync']) ? (bool) $input['auto_sync'] : false;
// 处理同步频率
if (isset($input['sync_interval'])) {
$allowed_intervals = array('hourly', 'twicedaily', 'daily', 'weekly');
$sanitized['sync_interval'] = in_array($input['sync_interval'], $allowed_intervals)
? $input['sync_interval']
: 'hourly';
}
// 更新定时任务
$this->update_cron_job($sanitized['sync_interval']);
return $sanitized;
}
/**
* 更新定时任务
*/
private function update_cron_job($interval) {
// 清除现有定时任务
wp_clear_scheduled_hook('wms_integration_sync_event');
// 添加新的定时任务
if (!wp_next_scheduled('wms_integration_sync_event')) {
wp_schedule_event(time(), $interval, 'wms_integration_sync_event');
}
}
/**
* 加载管理端脚本
*/
public function enqueue_admin_scripts($hook) {
if (strpos($hook, 'wms-integration') === false) {
return;
}
wp_enqueue_script(
'wms-integration-admin',
WMS_INTEGRATION_PLUGIN_URL . 'assets/js/admin.js',
array('jquery'),
WMS_INTEGRATION_VERSION,
true
);
wp_localize_script('wms-integration-admin', 'wms_integration_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('wms_integration_nonce'),
'testing' => '测试连接中...',
'syncing' => '同步中...',
));
wp_enqueue_style(
'wms-integration-admin',
WMS_INTEGRATION_PLUGIN_URL . 'assets/css/admin.css',
array(),
WMS_INTEGRATION_VERSION
);
}
}
库存同步与显示功能
库存同步是WMS集成的核心功能之一。以下代码实现库存同步和在前端显示实时库存:
<?php
/**
* 库存管理类
* 处理WMS库存与WordPress产品的同步
*/
class WMS_Integration_Inventory_Manager {
private $api_handler;
private $sync_in_progress = false;
public function __construct($api_handler) {
$this->api_handler = $api_handler;
// 添加库存同步钩子
add_action('wms_integration_sync_inventory', array($this, 'sync_all_inventory'));
// 在产品页面显示库存
add_filter('woocommerce_get_availability', array($this, 'display_wms_stock'), 10, 2);
// 在后台产品列表显示库存
add_action('woocommerce_product_set_stock', array($this, 'update_product_stock'));
add_action('woocommerce_variation_set_stock', array($this, 'update_variation_stock'));
}
/**
* 同步单个产品库存
* @param int $product_id 产品ID
* @return array 同步结果
*/
public function sync_product_stock($product_id) {
$product = wc_get_product($product_id);
if (!$product) {
return array(
'success' => false,
'error' => '产品不存在',
'product_id' => $product_id,
);
}
$sku = $product->get_sku();
if (empty($sku)) {
return array(
'success' => false,
'error' => '产品SKU为空',
'product_id' => $product_id,
);
}
// 从WMS获取库存
$result = $this->api_handler->get_stock($sku);
if ($result['success']) {
$wms_stock = intval($result['stock']);
// 更新WordPress库存
$product->set_stock_quantity($wms_stock);
$product->set_manage_stock(true);
// 根据库存设置库存状态
if ($wms_stock > 0) {
$product->set_stock_status('instock');
} else {
$product->set_stock_status('outofstock');
}
$product->save();
// 更新库存同步时间
update_post_meta($product_id, '_wms_stock_last_sync', current_time('mysql'));
update_post_meta($product_id, '_wms_stock_quantity', $wms_stock);
return array(
'success' => true,
'product_id' => $product_id,
'sku' => $sku,
'stock' => $wms_stock,
'message' => '库存同步成功',
);
}
return array(
'success' => false,
'error' => $result['error'] ?? '库存同步失败',
'product_id' => $product_id,
'sku' => $sku,
);
}
/**
* 同步所有产品库存
* 用于定时任务或批量同步
*/
public function sync_all_inventory() {
// 防止重复执行
if ($this->sync_in_progress) {
return;
}
$this->sync_in_progress = true;
// 获取所有需要管理库存的产品
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'fields' => 'ids',
'meta_query' => array(
array(
'key' => '_sku',
'compare' => 'EXISTS',
),
),
);
$product_ids = get_posts($args);
$results = array(
'success' => 0,
'failed' => 0,
'details' => array(),
);
foreach ($product_ids as $product_id) {
$result = $this->sync_product_stock($product_id);
if ($result['success']) {
$results['success']++;
} else {
$results['failed']++;
$results['details'][] = $result;
}
// 避免请求过于频繁
usleep(300000); // 0.3秒
}
$this->sync_in_progress = false;
// 记录同步日志
$this->log_sync_result($results);
return $results;
}
/**
* 在产品页面显示WMS库存信息
*/
public function display_wms_stock($availability, $product) {
$product_id = $product->get_id();
$wms_stock = get_post_meta($product_id, '_wms_stock_quantity', true);
$last_sync = get_post_meta($product_id, '_wms_stock_last_sync', true);
if ($wms_stock !== '') {
$wms_stock = intval($wms_stock);
// 添加WMS库存信息
if ($wms_stock > 0) {
$availability['availability'] = sprintf(
'库存: %d件 (WMS实时库存)',
$wms_stock
);
$availability['class'] = 'in-stock';
} else {
$availability['availability'] = '缺货 (WMS库存)';
$availability['class'] = 'out-of-stock';
}
// 添加最后同步时间
if ($last_sync) {
$sync_time = human_time_diff(strtotime($last_sync), current_time('timestamp'));
$availability['availability'] .= sprintf(
' - 最后同步: %s前',
$sync_time
);
}
}
return $availability;
}
/**
* 更新产品库存时触发WMS同步
*/
public function update_product_stock($product) {
// 只有在后台手动修改库存时才触发
if (is_admin() && $product->get_manage_stock()) {
$this->trigger_stock_update($product);
}
}
/**
* 更新变体库存时触发WMS同步
*/
public function update_variation_stock($variation) {
if (is_admin()) {
$this->trigger_stock_update($variation);
}
}
/**
* 触发库存更新到WMS
*/
private function trigger_stock_update($product) {
$product_id = $product->get_id();
$sku = $product->get_sku();
$stock = $product->get_stock_quantity();
if (empty($sku)) {
return;
}
// 准备库存更新数据
$stock_data = array(
'sku' => $sku,
'stock' => $stock,
'product_id' => $product_id,
'update_time' => current_time('mysql'),
);
// 发送到WMS(这里需要根据WMS API调整)
// $this->api_handler->update_stock($stock_data);
// 记录本地更新
update_post_meta($product_id, '_wms_stock_updated', current_time('mysql'));
update_post_meta($product_id, '_wms_stock_manual_update', $stock);
}
/**
* 记录同步日志
*/
private function log_sync_result($results) {
$log_entry = array(
'timestamp' => current_time('mysql'),
'total' => $results['success'] + $results['failed'],
'success' => $results['success'],
'failed' => $results['failed'],
'details' => $results['details'],
);
// 获取现有日志
$logs = get_option('wms_inventory_sync_logs', array());
// 限制日志数量(保留最近50条)
array_unshift($logs, $log_entry);
if (count($logs) > 50) {
$logs = array_slice($logs, 0, 50);
}
update_option('wms_inventory_sync_logs', $logs);
}
/**
* 获取同步日志
*/
public function get_sync_logs($limit = 10) {
$logs = get_option('wms_inventory_sync_logs', array());
return array_slice($logs, 0, $limit);
}
}
核心插件类与AJAX处理
最后,我们创建核心插件类和AJAX处理函数:
<?php
/**
* 核心插件类
* 初始化所有组件并协调工作
*/
class WMS_Integration_Core {
private $api_handler;
private $order_sync;
private $inventory_manager;
private $admin_settings;
public function __construct() {
// 初始化组件
$this->init_components();
// 注册AJAX处理函数
$this->register_ajax_handlers();
}
/**
* 初始化所有组件
*/
private function init_components() {
// 获取设置
$settings = get_option('wms_integration_settings', array());
// 初始化API处理器
$api_url = isset($settings['api_url']) ? $settings['api_url'] : '';
$api_key = isset($settings['api_key']) ? $settings['api_key'] : '';
$this->api_handler = new WMS_Integration_API_Handler($api_url, $api_key);
// 初始化订单同步
