文章目录[隐藏]
WordPress文创插件实现柔性库存管理的分步教程
引言:为什么文创产品需要柔性库存管理?
文创产品与传统商品不同,通常具有以下特点:
- 限量生产或预售模式
- 季节性、节日性销售波动
- 定制化需求较多
- 原材料采购周期长
- 多销售渠道库存同步需求
传统的库存管理系统往往无法满足这些特殊需求。本文将详细介绍如何通过开发WordPress插件,为文创产品实现柔性库存管理解决方案。
准备工作:环境与工具配置
在开始开发前,确保您的环境满足以下要求:
<?php
/**
* WordPress文创库存管理插件 - 环境检查
*
* 此代码用于检查运行环境是否满足插件需求
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
class WC_Flexible_Inventory_Checker {
/**
* 检查系统要求
* @return array 检查结果
*/
public static function check_requirements() {
$results = array();
// 检查PHP版本
$results['php_version'] = array(
'requirement' => 'PHP 7.0或更高版本',
'current' => PHP_VERSION,
'met' => version_compare(PHP_VERSION, '7.0.0', '>=')
);
// 检查WordPress版本
$results['wp_version'] = array(
'requirement' => 'WordPress 5.0或更高版本',
'current' => get_bloginfo('version'),
'met' => version_compare(get_bloginfo('version'), '5.0.0', '>=')
);
// 检查WooCommerce是否安装
$results['woocommerce'] = array(
'requirement' => 'WooCommerce插件',
'current' => defined('WC_VERSION') ? WC_VERSION : '未安装',
'met' => class_exists('WooCommerce')
);
// 检查MySQL版本
global $wpdb;
$results['mysql_version'] = array(
'requirement' => 'MySQL 5.6或更高版本',
'current' => $wpdb->db_version(),
'met' => version_compare($wpdb->db_version(), '5.6.0', '>=')
);
return $results;
}
/**
* 显示检查结果
*/
public static function display_results() {
$results = self::check_requirements();
$all_met = true;
echo '<div class="notice notice-info">';
echo '<h3>系统环境检查</h3>';
echo '<ul>';
foreach ($results as $key => $result) {
$status = $result['met'] ? '✅' : '❌';
$all_met = $all_met && $result['met'];
echo sprintf(
'<li>%s %s: %s (当前: %s)</li>',
$status,
ucfirst(str_replace('_', ' ', $key)),
$result['requirement'],
$result['current']
);
}
echo '</ul>';
if ($all_met) {
echo '<p style="color:green;">✅ 所有要求均已满足,可以继续安装插件。</p>';
} else {
echo '<p style="color:red;">❌ 部分要求未满足,请先解决上述问题。</p>';
}
echo '</div>';
}
}
// 在管理后台显示检查结果
add_action('admin_notices', array('WC_Flexible_Inventory_Checker', 'display_results'));
?>
第一步:创建插件基础结构
创建插件主文件 flexible-inventory-manager.php:
<?php
/**
* Plugin Name: WordPress文创柔性库存管理器
* Plugin URI: https://yourwebsite.com/
* Description: 为文创产品提供柔性库存管理解决方案
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: wc-flexible-inventory
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('WC_FIM_VERSION', '1.0.0');
define('WC_FIM_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WC_FIM_PLUGIN_URL', plugin_dir_url(__FILE__));
/**
* 主插件类
*/
class WC_Flexible_Inventory_Manager {
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();
$this->includes();
}
/**
* 初始化钩子
*/
private function init_hooks() {
// 激活/停用钩子
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// 初始化
add_action('plugins_loaded', array($this, 'init'));
// 加载文本域
add_action('init', array($this, 'load_textdomain'));
}
/**
* 包含必要文件
*/
private function includes() {
// 核心功能
require_once WC_FIM_PLUGIN_DIR . 'includes/class-inventory-db.php';
require_once WC_FIM_PLUGIN_DIR . 'includes/class-flexible-product.php';
require_once WC_FIM_PLUGIN_DIR . 'includes/class-inventory-sync.php';
// 管理界面
if (is_admin()) {
require_once WC_FIM_PLUGIN_DIR . 'admin/class-admin-settings.php';
require_once WC_FIM_PLUGIN_DIR . 'admin/class-inventory-reports.php';
}
}
/**
* 激活插件
*/
public function activate() {
// 创建数据库表
WC_FIM_Inventory_DB::create_tables();
// 设置默认选项
update_option('wc_fim_version', WC_FIM_VERSION);
update_option('wc_fim_enable_flexible_inventory', 'yes');
update_option('wc_fim_low_stock_threshold', 10);
update_option('wc_fim_enable_preorder', 'yes');
}
/**
* 停用插件
*/
public function deactivate() {
// 清理临时数据
wp_clear_scheduled_hook('wc_fim_daily_inventory_sync');
}
/**
* 初始化插件
*/
public function init() {
// 检查依赖
if (!$this->check_dependencies()) {
return;
}
// 初始化核心类
new WC_FIM_Flexible_Product();
new WC_FIM_Inventory_Sync();
if (is_admin()) {
new WC_FIM_Admin_Settings();
new WC_FIM_Inventory_Reports();
}
}
/**
* 检查依赖
*/
private function check_dependencies() {
if (!class_exists('WooCommerce')) {
add_action('admin_notices', function() {
echo '<div class="error"><p>';
echo __('文创库存管理器需要WooCommerce插件。请先安装并激活WooCommerce。', 'wc-flexible-inventory');
echo '</p></div>';
});
return false;
}
return true;
}
/**
* 加载文本域
*/
public function load_textdomain() {
load_plugin_textdomain(
'wc-flexible-inventory',
false,
dirname(plugin_basename(__FILE__)) . '/languages'
);
}
}
// 启动插件
WC_Flexible_Inventory_Manager::get_instance();
?>
第二步:实现柔性库存数据库结构
创建 includes/class-inventory-db.php:
<?php
/**
* 库存数据库管理类
*/
class WC_FIM_Inventory_DB {
/**
* 创建数据库表
*/
public static function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'wc_fim_flexible_inventory';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
product_id bigint(20) NOT NULL,
variant_id bigint(20) DEFAULT 0,
physical_stock int(11) DEFAULT 0,
reserved_stock int(11) DEFAULT 0,
preorder_stock int(11) DEFAULT 0,
max_preorder int(11) DEFAULT 0,
low_stock_threshold int(11) DEFAULT 10,
allow_backorder tinyint(1) DEFAULT 0,
backorder_limit int(11) DEFAULT 0,
last_synced datetime DEFAULT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY product_variant (product_id, variant_id),
KEY idx_product_id (product_id),
KEY idx_variant_id (variant_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 创建库存日志表
$log_table = $wpdb->prefix . 'wc_fim_inventory_logs';
$log_sql = "CREATE TABLE IF NOT EXISTS $log_table (
id bigint(20) NOT NULL AUTO_INCREMENT,
inventory_id bigint(20) NOT NULL,
product_id bigint(20) NOT NULL,
variant_id bigint(20) DEFAULT 0,
order_id bigint(20) DEFAULT NULL,
user_id bigint(20) DEFAULT NULL,
action varchar(50) NOT NULL,
old_value text,
new_value text,
quantity_change int(11) DEFAULT 0,
note text,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_inventory_id (inventory_id),
KEY idx_product_id (product_id),
KEY idx_created_at (created_at)
) $charset_collate;";
dbDelta($log_sql);
}
/**
* 获取产品库存数据
*/
public static function get_product_inventory($product_id, $variant_id = 0) {
global $wpdb;
$table = $wpdb->prefix . 'wc_fim_flexible_inventory';
return $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $table WHERE product_id = %d AND variant_id = %d",
$product_id,
$variant_id
));
}
/**
* 更新库存数据
*/
public static function update_inventory($data) {
global $wpdb;
$table = $wpdb->prefix . 'wc_fim_flexible_inventory';
// 检查记录是否存在
$existing = self::get_product_inventory(
$data['product_id'],
$data['variant_id'] ?? 0
);
if ($existing) {
// 更新现有记录
$wpdb->update(
$table,
$data,
array(
'product_id' => $data['product_id'],
'variant_id' => $data['variant_id'] ?? 0
)
);
return $existing->id;
} else {
// 插入新记录
$wpdb->insert($table, $data);
return $wpdb->insert_id;
}
}
/**
* 记录库存变更
*/
public static function log_inventory_change($log_data) {
global $wpdb;
$table = $wpdb->prefix . 'wc_fim_inventory_logs';
$wpdb->insert($table, $log_data);
return $wpdb->insert_id;
}
}
?>
第三步:扩展WooCommerce产品设置
创建 includes/class-flexible-product.php:
<?php
/**
* 柔性产品管理类
*/
class WC_FIM_Flexible_Product {
public function __construct() {
// 添加产品数据标签
add_filter('woocommerce_product_data_tabs', array($this, 'add_inventory_tab'));
// 添加产品数据面板
add_action('woocommerce_product_data_panels', array($this, 'add_inventory_panel'));
// 保存产品数据
add_action('woocommerce_process_product_meta', array($this, 'save_inventory_settings'));
// 覆盖库存检查
add_filter('woocommerce_product_is_in_stock', array($this, 'check_flexible_stock'), 10, 2);
// 添加库存显示
add_filter('woocommerce_get_availability', array($this, 'display_flexible_availability'), 10, 2);
}
/**
* 添加库存管理标签页
*/
public function add_inventory_tab($tabs) {
$tabs['flexible_inventory'] = array(
'label' => __('柔性库存', 'wc-flexible-inventory'),
'target' => 'flexible_inventory_data',
'class' => array('show_if_simple', 'show_if_variable'),
'priority' => 21,
);
return $tabs;
}
/**
* 添加库存管理面板
*/
public function add_inventory_panel() {
global $post;
$product = wc_get_product($post->ID);
$inventory_data = WC_FIM_Inventory_DB::get_product_inventory($post->ID);
?>
<div id="flexible_inventory_data" class="panel woocommerce_options_panel">
<div class="options_group">
<?php
// 物理库存
woocommerce_wp_text_input(array(
'id' => '_fim_physical_stock',
'label' => __('物理库存', 'wc-flexible-inventory'),
'description' => __('实际仓库中的库存数量', 'wc-flexible-inventory'),
'desc_tip' => true,
'type' => 'number',
'value' => $inventory_data ? $inventory_data->physical_stock : 0,
));
// 预售库存
woocommerce_wp_text_input(array(
'id' => '_fim_preorder_stock',
'label' => __('预售库存', 'wc-flexible-inventory'),
'description' => __('允许预售的最大数量', 'wc-flexible-inventory'),
'desc_tip' => true,
'type' => 'number',
'value' => $inventory_data ? $inventory_data->preorder_stock : 0,
));
// 允许缺货订购
woocommerce_wp_checkbox(array(
'id' => '_fim_allow_backorder',
'label' => __('允许缺货订购', 'wc-flexible-inventory'),
'description' => __('允许客户在缺货时继续下单', 'wc-flexible-inventory'),
'value' => $inventory_data ? $inventory_data->allow_backorder : 'no',
));
// 缺货订购限制
woocommerce_wp_text_input(array(
'id' => '_fim_backorder_limit',
'label' => __('缺货订购限制', 'wc-flexible-inventory'),
'description' => __('最大缺货订购数量(0表示无限制)', 'wc-flexible-inventory'),
'desc_tip' => true,
'type' => 'number',
'value' => $inventory_data ? $inventory_data->backorder_limit : 0,
));
// 低库存阈值
woocommerce_wp_text_input(array(
'id' => '_fim_low_stock_threshold',
'label' => __('低库存阈值', 'wc-flexible-inventory'),
'description' => __('触发低库存警告的数量', 'wc-flexible-inventory'),
'desc_tip' => true,
'type' => 'number',
'value' => $inventory_data ? $inventory_data->low_stock_threshold : 10,
));
?>
</div>
<div class="options_group">
<h3><?php _e('当前库存状态', 'wc-flexible-inventory'); ?></h3>
<?php if ($inventory_data): ?>
<p>
<?php _e('可用库存:', 'wc-flexible-inventory'); ?>
<strong><?php echo $this->calculate_available_stock($inventory_data); ?></strong>
</p>
<p>
<?php _e('预留库存:', 'wc-flexible-inventory'); ?>
<strong><?php echo $inventory_data->reserved_stock; ?></strong>
</p>
<?php endif; ?>
</div>
</div>
<?php
}
/**
* 保存库存设置
*/
public function save_inventory_settings($product_id) {
$product = wc_get_product($product_id);
$inventory_data = array(
'product_id' => $product_id,
'physical_stock' => isset($_POST['_fim_physical_stock']) ? intval($_POST['_fim_physical_stock']) : 0,
'preorder_stock' => isset($_POST['_fim_preorder_stock']) ? intval($_POST['_fim_preorder_stock']) : 0,
'allow_backorder' => isset($_POST['_fim_allow_backorder']) ? 1 : 0,
'backorder_limit' => isset($_POST['_fim_backorder_limit']) ? intval($_POST['_fim_backorder_limit']) : 0,
low_stock_threshold' => isset($_POST['_fim_low_stock_threshold']) ? intval($_POST['_fim_low_stock_threshold']) : 10,
);
// 如果是变体产品
if ($product->is_type('variable')) {
$variations = $product->get_children();
foreach ($variations as $variation_id) {
$inventory_data['variant_id'] = $variation_id;
WC_FIM_Inventory_DB::update_inventory($inventory_data);
}
} else {
// 简单产品
$inventory_data['variant_id'] = 0;
WC_FIM_Inventory_DB::update_inventory($inventory_data);
}
}
/**
* 计算可用库存
*/
private function calculate_available_stock($inventory_data) {
// 可用库存 = 物理库存 + 预售库存 - 预留库存
return $inventory_data->physical_stock +
$inventory_data->preorder_stock -
$inventory_data->reserved_stock;
}
/**
* 检查柔性库存
*/
public function check_flexible_stock($in_stock, $product) {
$product_id = $product->get_id();
$variant_id = 0;
// 如果是变体,获取变体ID
if ($product->is_type('variation')) {
$product_id = $product->get_parent_id();
$variant_id = $product->get_id();
}
$inventory = WC_FIM_Inventory_DB::get_product_inventory($product_id, $variant_id);
if (!$inventory) {
return $in_stock;
}
$available_stock = $this->calculate_available_stock($inventory);
// 如果有可用库存或允许缺货订购
if ($available_stock > 0 || $inventory->allow_backorder) {
return true;
}
return false;
}
/**
* 显示柔性库存可用性
*/
public function display_flexible_availability($availability, $product) {
$product_id = $product->get_id();
$variant_id = 0;
if ($product->is_type('variation')) {
$product_id = $product->get_parent_id();
$variant_id = $product->get_id();
}
$inventory = WC_FIM_Inventory_DB::get_product_inventory($product_id, $variant_id);
if (!$inventory) {
return $availability;
}
$available_stock = $this->calculate_available_stock($inventory);
if ($available_stock <= 0 && $inventory->allow_backorder) {
$availability['class'] = 'available-on-backorder';
$availability['availability'] = __('可缺货订购', 'wc-flexible-inventory');
} elseif ($available_stock <= 0) {
$availability['class'] = 'out-of-stock';
$availability['availability'] = __('缺货', 'wc-flexible-inventory');
} elseif ($available_stock <= $inventory->low_stock_threshold) {
$availability['class'] = 'low-stock';
$availability['availability'] = sprintf(__('仅剩 %d 件', 'wc-flexible-inventory'), $available_stock);
}
return $availability;
}
}
?>
## 第四步:实现库存同步与订单处理
创建 `includes/class-inventory-sync.php`:
<?php
/**
- 库存同步管理类
*/
class WC_FIM_Inventory_Sync {
public function __construct() {
// 订单状态变更时更新库存
add_action('woocommerce_order_status_changed', array($this, 'update_inventory_on_order_change'), 10, 4);
// 添加每日库存同步任务
add_action('wc_fim_daily_inventory_sync', array($this, 'daily_sync'));
// 计划每日同步任务
if (!wp_next_scheduled('wc_fim_daily_inventory_sync')) {
wp_schedule_event(time(), 'daily', 'wc_fim_daily_inventory_sync');
}
// REST API端点
add_action('rest_api_init', array($this, 'register_rest_routes'));
}
/**
* 订单状态变更时更新库存
*/
public function update_inventory_on_order_change($order_id, $old_status, $new_status, $order) {
$items = $order->get_items();
foreach ($items as $item) {
$product = $item->get_product();
$quantity = $item->get_quantity();
if (!$product) {
continue;
}
$product_id = $product->get_id();
$variant_id = 0;
if ($product->is_type('variation')) {
$product_id = $product->get_parent_id();
$variant_id = $product->get_id();
}
$inventory = WC_FIM_Inventory_DB::get_product_inventory($product_id, $variant_id);
if (!$inventory) {
continue;
}
// 根据订单状态更新库存
switch ($new_status) {
case 'processing':
case 'on-hold':
// 预留库存
$this->reserve_stock($inventory, $quantity, $order_id);
break;
case 'completed':
// 扣减物理库存
$this->deduct_physical_stock($inventory, $quantity, $order_id);
break;
case 'cancelled':
case 'refunded':
// 释放预留库存
$this->release_reserved_stock($inventory, $quantity, $order_id);
break;
}
}
}
/**
* 预留库存
*/
private function reserve_stock($inventory, $quantity, $order_id) {
global $wpdb;
$table = $wpdb->prefix . 'wc_fim_flexible_inventory';
$wpdb->query($wpdb->prepare(
"UPDATE $table SET reserved_stock = reserved_stock + %d WHERE id = %d",
$quantity,
$inventory->id
));
// 记录库存变更
WC_FIM_Inventory_DB::log_inventory_change(array(
'inventory_id' => $inventory->id,
'product_id' => $inventory->product_id,
'variant_id' => $inventory->variant_id,
'order_id' => $order_id,
'action' => 'reserve',
'quantity_change' => $quantity,
'note' => sprintf('订单 #%d 预留库存', $order_id)
));
}
/**
* 扣减物理库存
*/
private function deduct_physical_stock($inventory, $quantity, $order_id) {
global $wpdb;
$table = $wpdb->prefix . 'wc_fim_flexible_inventory';
$wpdb->query($wpdb->prepare(
"UPDATE $table SET
physical_stock = GREATEST(0, physical_stock - %d),
reserved_stock = GREATEST(0, reserved_stock - %d)
WHERE id = %d",
$quantity,
$quantity,
$inventory->id
));
// 记录库存变更
WC_FIM_Inventory_DB::log_inventory_change(array(
'inventory_id' => $inventory->id,
'product_id' => $inventory->product_id,
'variant_id' => $inventory->variant_id,
'order_id' => $order_id,
'action' => 'deduct',
'quantity_change' => -$quantity,
'note' => sprintf('订单 #%d 发货扣减', $order_id)
));
}
/**
* 释放预留库存
*/
private function release_reserved_stock($inventory, $quantity, $order_id) {
global $wpdb;
$table = $wpdb->prefix . 'wc_fim_flexible_inventory';
$wpdb->query($wpdb->prepare(
"UPDATE $table SET reserved_stock = GREATEST(0, reserved_stock - %d) WHERE id = %d",
$quantity,
$inventory->id
));
// 记录库存变更
WC_FIM_Inventory_DB::log_inventory_change(array(
'inventory_id' => $inventory->id,
'product_id' => $inventory->product_id,
'variant_id' => $inventory->variant_id,
'order_id' => $order_id,
'action' => 'release',
'quantity_change' => $quantity,
'note' => sprintf('订单 #%d 取消/退款', $order_id)
));
}
/**
* 每日库存同步
*/
public function daily_sync() {
global $wpdb;
$table = $wpdb->prefix . 'wc_fim_flexible_inventory';
// 更新同步时间
$wpdb->query("UPDATE $table SET last_synced = NOW()");
// 检查低库存并发送通知
$this->check_low_stock();
// 同步外部库存(如果有的话)
$this->sync_external_inventory();
}
/**
* 检查低库存
*/
private function check_low_stock() {
global $wpdb;
$table = $wpdb->prefix . 'wc_fim_flexible_inventory';
$low_stock_items = $wpdb->get_results("
SELECT i.*, p.post_title as product_name
FROM $table i
LEFT JOIN {$wpdb->posts} p ON i.product_id = p.ID
WHERE (i.physical_stock + i.preorder_stock - i.reserved_stock) <= i.low_stock_threshold
AND i.physical_stock + i.preorder_stock > 0
");
if (!empty($low_stock_items)) {
$this->send_low_stock_notification($low_stock_items);
}
}
/**
* 发送低库存通知
*/
private function send_low_stock_notification($items) {
$admin_email = get_option('admin_email');
$subject = sprintf(__('[%s] 低库存警告', 'wc-flexible-inventory'), get_bloginfo('name'));
$message = __('以下产品库存较低:', 'wc-flexible-inventory') . "nn";
foreach ($items as $item) {
$available = $item->physical_stock + $item->preorder_stock - $item->reserved_stock;
$message .= sprintf(
__('产品: %s, 可用库存: %d, 阈值: %d', 'wc-flexible-inventory'),
$item->product_name,
$available,
$item->low_stock_threshold
) . "n";
}
$message .= "n" . __('请及时补充库存。', 'wc-flexible-inventory');
wp_mail($admin_email, $subject, $message);
}
/**
* 同步外部库存
*/
private function sync_external_inventory() {
// 这里可以集成外部库存系统
// 例如:ERP系统、供应商API等
$external_sync_enabled = get_option('wc_fim_enable_external_sync', 'no');
if ($external_sync_enabled === 'yes') {
// 调用外部API同步库存
// $this->sync_with_external_api();
}
}
/**
* 注册REST API路由
*/
public function register_rest_routes() {
register_rest_route('wc-fim/v1', '/inventory/(?P<id>d+)', array(
'methods' => 'GET',
'callback' => array($this, 'get_inventory_api'),
'permission_callback' => array($this, 'check_api_permission'),
'args' => array(
'id' => array(
'validate_callback' => 'is_numeric'
),
),
));
register_rest_route('wc-fim/v1', '/inventory/update', array(
'methods' => 'POST',
'callback' => array($this, 'update_inventory_api'),
'permission_callback' => array($this, 'check_api_permission'),
));
}
/**
* 获取库存API
*/
public function get_inventory_api($request) {
$product_id = $request['id'];
$variant_id = $request->get_param('variant_id') ?: 0;
$inventory = WC_FIM_Inventory_DB::get_product_inventory($product_id, $variant_id);
if (!$inventory) {
return new WP_Error('not_found', __('库存记录未找到', 'wc-flexible-inventory'), array('status' => 404));
}
return rest_ensure_response(array(
'success' => true,
'data' => $inventory
));
}
/**
* 更新库存API
*/
public function update_inventory_api($request) {
$params = $request->get_json_params();
if (!isset($params['product_id'])) {
return new WP_Error('missing_params', __('缺少必要参数', 'wc-flexible-inventory'), array('status' => 400));
}
$result = WC_FIM_Inventory_DB::update_inventory($params);
return rest_ensure_response(array(
'success' => true,
'message' => __('库存更新成功', 'wc-flexible-inventory'),
'inventory_id' => $result
));
}
/**
* 检查API权限
*/
public function check_api_permission($request) {
// 这里可以添加API密钥验证
$api_key = $request->get_header('X-API-Key');
$valid_key = get_option('wc_fim_api_key');
if ($valid_key && $api_key === $valid_key) {
return true;
}
return current_user_can('manage_woocommerce');
}
}
?>
## 第五步:创建管理界面与报表
创建 `admin/class-admin-settings.php`:
<?php
/**
- 管理设置类
*/
class WC_FIM_Admin_Settings {
public function __construct() {
// 添加设置页面
add_action('admin_menu', array($this, 'add_admin_menu'));
// 注册设置
add_action('admin_init', array($this, 'register_settings'));
// 添加库存管理列
add_filter('manage_product_posts_columns', array($this, 'add_inventory_columns'));
add_action('manage_product_posts_custom_column', array($this, 'display_inventory_columns'), 10, 2);
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_submenu_page(
'woocommerce',
__('柔性库存管理', 'wc-flexible-inventory'),
__('柔性库存', 'wc-flexible-inventory'),
'manage_woocommerce',
'wc-flexible-inventory',
array($this, 'display_settings_page')
);
}
/**
* 显示设置页面
*/
public function display_settings_page() {
?>
<div class="wrap">
<h1><?php _e('文创柔性库存管理设置', 'wc-flexible-inventory'); ?></h1>
<form method="post" action="options.php">
<?php
settings_fields('wc_fim_settings_group');
do_settings_sections('wc-flexible-inventory');
submit_button();
?>
</form>
<div class="wc-fim-dashboard">
<h2><?php _e('库存概览', 'wc-flexible-inventory'); ?></h2>
<?php $this->display_inventory_overview(); ?>
</div>
</div>
<?php
}
/**
* 注册设置
*/
public function register_settings() {
register_setting('wc_fim_settings_group', 'wc_fim_enable_flexible_inventory');
register_setting('wc_fim_settings_group', 'wc_fim_low_stock_threshold');
register_setting('wc_fim_settings_group', 'wc_fim_enable_preorder');
register_setting('wc_fim_settings_group', 'wc_fim_enable_external_sync');
register_setting('wc_fim_settings_group', 'wc_fim_api_key');
add_settings_section(
'wc_fim_general_section',
__('常规设置', 'wc-flexible-inventory'),
array($this, 'general_section_callback'),
'wc-flexible-inventory'
);
add_settings_field(
'wc_fim_enable_flexible_inventory',
__('启用柔性库存', 'wc-flexible-inventory'),
array($this, 'checkbox_field_callback'),
'wc-flexible-inventory',
'wc_fim_general_section',
array(
'label_for' => 'wc_fim_enable_flexible_inventory',
'description' => __('启用文创产品的柔性库存管理功能', 'wc-flexible-inventory')
)
);
add_settings_field(
'wc_fim_low_stock_threshold',
__('全局低库存阈值', 'wc-flexible-inventory'),
array($this, 'number_field_callback'),
'wc-flexible-inventory',
'wc_fim_general_section',
array(
'label_for' => 'wc_fim_low_stock_threshold',
'description' => __('触发低库存警告的默认数量', 'wc-flexible-inventory'),
'default' => 10
)
);
add_settings_field(
'wc_fim_enable_preorder',
__('启用预售功能', 'wc-flexible-inventory'),
array($this, 'checkbox_field_callback'),
'wc-flexible-inventory
