首页 / 教程文章 / 实现小批量动态库存预警的WordPress插件开发教程

实现小批量动态库存预警的WordPress插件开发教程

实现小批量动态库存预警的WordPress插件开发教程

概述

在电子商务网站运营中,库存管理是至关重要的环节。对于小型企业或初创电商来说,一个简单而有效的库存预警系统可以避免缺货损失,同时减少过度库存带来的资金压力。本教程将指导您开发一个适用于WordPress的小批量动态库存预警插件,该插件能够在库存低于设定阈值时自动发送预警通知。

插件功能规划

我们的插件将具备以下核心功能:

  1. 在商品编辑页面添加库存预警阈值设置字段
  2. 实时监控库存变化
  3. 当库存低于阈值时发送邮件通知管理员
  4. 在后台管理界面显示库存预警状态
  5. 支持批量设置预警阈值

开发环境准备

在开始开发前,请确保您已具备以下环境:

  • WordPress 5.0或更高版本
  • PHP 7.2或更高版本
  • 基础的WordPress插件开发知识
  • 文本编辑器或IDE(如VS Code、PHPStorm)

创建插件基础结构

首先,在WordPress的wp-content/plugins目录下创建一个新文件夹,命名为dynamic-stock-alert。在该文件夹中创建以下文件结构:

dynamic-stock-alert/
├── dynamic-stock-alert.php      # 主插件文件
├── includes/
│   ├── class-admin-settings.php # 后台设置类
│   ├── class-stock-monitor.php  # 库存监控类
│   └── class-email-notifier.php # 邮件通知类
├── assets/
│   ├── css/
│   │   └── admin-style.css      # 后台样式
│   └── js/
│       └── admin-script.js      # 后台脚本
└── uninstall.php                # 卸载清理脚本

主插件文件实现

打开dynamic-stock-alert.php文件,添加以下代码:

<?php
/**
 * Plugin Name: 小批量动态库存预警
 * Plugin URI: https://yourwebsite.com/
 * Description: 一个用于监控WooCommerce库存并在库存低于阈值时发送预警通知的插件
 * Version: 1.0.0
 * Author: 您的名字
 * License: GPL v2 or later
 * Text Domain: dynamic-stock-alert
 */

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

// 定义插件常量
define('DSA_VERSION', '1.0.0');
define('DSA_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('DSA_PLUGIN_URL', plugin_dir_url(__FILE__));

// 检查WooCommerce是否激活
function dsa_check_woocommerce() {
    if (!class_exists('WooCommerce')) {
        add_action('admin_notices', function() {
            ?>
            <div class="notice notice-error">
                <p><?php _e('小批量动态库存预警插件需要WooCommerce才能正常工作。请安装并激活WooCommerce插件。', 'dynamic-stock-alert'); ?></p>
            </div>
            <?php
        });
        return false;
    }
    return true;
}

// 初始化插件
function dsa_init_plugin() {
    if (!dsa_check_woocommerce()) {
        return;
    }
    
    // 包含必要文件
    require_once DSA_PLUGIN_DIR . 'includes/class-admin-settings.php';
    require_once DSA_PLUGIN_DIR . 'includes/class-stock-monitor.php';
    require_once DSA_PLUGIN_DIR . 'includes/class-email-notifier.php';
    
    // 初始化各个组件
    new DSA_Admin_Settings();
    new DSA_Stock_Monitor();
    new DSA_Email_Notifier();
}
add_action('plugins_loaded', 'dsa_init_plugin');

// 激活插件时的操作
function dsa_activate_plugin() {
    // 创建必要的数据库表(如果需要)
    global $wpdb;
    $table_name = $wpdb->prefix . 'stock_alert_logs';
    
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        product_id bigint(20) NOT NULL,
        product_name varchar(255) NOT NULL,
        current_stock int(11) NOT NULL,
        threshold int(11) NOT NULL,
        alert_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        notified tinyint(1) DEFAULT 0,
        PRIMARY KEY (id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 设置默认选项
    add_option('dsa_default_threshold', 10);
    add_option('dsa_admin_email', get_option('admin_email'));
    add_option('dsa_email_subject', '库存预警通知');
    add_option('dsa_email_frequency', 'daily');
}
register_activation_hook(__FILE__, 'dsa_activate_plugin');

// 停用插件时的清理操作
function dsa_deactivate_plugin() {
    // 清理定时任务
    wp_clear_scheduled_hook('dsa_daily_stock_check');
}
register_deactivation_hook(__FILE__, 'dsa_deactivate_plugin');

后台设置类实现

创建includes/class-admin-settings.php文件:

<?php
/**
 * 后台设置管理类
 */
class DSA_Admin_Settings {
    
    public function __construct() {
        // 添加商品编辑页面的库存预警字段
        add_action('woocommerce_product_options_inventory_product_data', array($this, 'add_stock_alert_field'));
        add_action('woocommerce_process_product_meta', array($this, 'save_stock_alert_field'));
        
        // 添加批量编辑功能
        add_action('woocommerce_product_bulk_edit_end', array($this, 'add_bulk_edit_field'));
        add_action('woocommerce_product_bulk_edit_save', array($this, 'save_bulk_edit_field'));
        
        // 添加后台菜单
        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_assets'));
    }
    
    /**
     * 在商品编辑页面添加库存预警阈值字段
     */
    public function add_stock_alert_field() {
        global $post;
        
        echo '<div class="options_group">';
        
        woocommerce_wp_text_input(array(
            'id'          => '_stock_alert_threshold',
            'label'       => __('库存预警阈值', 'dynamic-stock-alert'),
            'desc_tip'    => true,
            'description' => __('当库存低于此数值时,系统将发送预警通知。留空则使用全局默认值。', 'dynamic-stock-alert'),
            'type'        => 'number',
            'value'       => get_post_meta($post->ID, '_stock_alert_threshold', true),
            'placeholder' => get_option('dsa_default_threshold', 10)
        ));
        
        echo '</div>';
    }
    
    /**
     * 保存库存预警阈值字段
     */
    public function save_stock_alert_field($product_id) {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (isset($_POST['_stock_alert_threshold'])) {
            $threshold = sanitize_text_field($_POST['_stock_alert_threshold']);
            update_post_meta($product_id, '_stock_alert_threshold', $threshold);
        }
    }
    
    /**
     * 添加批量编辑字段
     */
    public function add_bulk_edit_field() {
        ?>
        <div class="inline-edit-group">
            <label class="alignleft">
                <span class="title"><?php _e('库存预警阈值', 'dynamic-stock-alert'); ?></span>
                <span class="input-text-wrap">
                    <input type="number" name="_bulk_stock_alert_threshold" class="text" value="" placeholder="<?php echo get_option('dsa_default_threshold', 10); ?>">
                </span>
            </label>
            <p class="description"><?php _e('设置选中商品的库存预警阈值', 'dynamic-stock-alert'); ?></p>
        </div>
        <?php
    }
    
    /**
     * 保存批量编辑字段
     */
    public function save_bulk_edit_field($product) {
        $product_id = $product->get_id();
        
        if (isset($_REQUEST['_bulk_stock_alert_threshold'])) {
            $threshold = sanitize_text_field($_REQUEST['_bulk_stock_alert_threshold']);
            if (!empty($threshold)) {
                update_post_meta($product_id, '_stock_alert_threshold', $threshold);
            }
        }
    }
    
    /**
     * 添加后台菜单
     */
    public function add_admin_menu() {
        add_submenu_page(
            'woocommerce',
            __('库存预警设置', 'dynamic-stock-alert'),
            __('库存预警', 'dynamic-stock-alert'),
            'manage_options',
            'dsa-settings',
            array($this, 'render_settings_page')
        );
    }
    
    /**
     * 渲染设置页面
     */
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1><?php _e('小批量动态库存预警设置', 'dynamic-stock-alert'); ?></h1>
            
            <form method="post" action="options.php">
                <?php
                settings_fields('dsa_settings_group');
                do_settings_sections('dsa-settings');
                submit_button();
                ?>
            </form>
            
            <div class="dsa-dashboard">
                <h2><?php _e('当前库存预警状态', 'dynamic-stock-alert'); ?></h2>
                <?php $this->render_alert_status(); ?>
            </div>
        </div>
        <?php
    }
    
    /**
     * 注册设置
     */
    public function register_settings() {
        register_setting('dsa_settings_group', 'dsa_default_threshold');
        register_setting('dsa_settings_group', 'dsa_admin_email');
        register_setting('dsa_settings_group', 'dsa_email_subject');
        register_setting('dsa_settings_group', 'dsa_email_frequency');
        
        add_settings_section(
            'dsa_general_section',
            __('常规设置', 'dynamic-stock-alert'),
            null,
            'dsa-settings'
        );
        
        add_settings_field(
            'dsa_default_threshold',
            __('默认预警阈值', 'dynamic-stock-alert'),
            array($this, 'render_threshold_field'),
            'dsa-settings',
            'dsa_general_section'
        );
        
        add_settings_field(
            'dsa_admin_email',
            __('通知邮箱', 'dynamic-stock-alert'),
            array($this, 'render_email_field'),
            'dsa-settings',
            'dsa_general_section'
        );
        
        add_settings_field(
            'dsa_email_subject',
            __('邮件主题', 'dynamic-stock-alert'),
            array($this, 'render_subject_field'),
            'dsa-settings',
            'dsa_general_section'
        );
        
        add_settings_field(
            'dsa_email_frequency',
            __('检查频率', 'dynamic-stock-alert'),
            array($this, 'render_frequency_field'),
            'dsa-settings',
            'dsa_general_section'
        );
    }
    
    /**
     * 渲染阈值字段
     */
    public function render_threshold_field() {
        $value = get_option('dsa_default_threshold', 10);
        echo '<input type="number" name="dsa_default_threshold" value="' . esc_attr($value) . '" min="1" class="small-text">';
        echo '<p class="description">' . __('当商品未单独设置阈值时使用的默认值', 'dynamic-stock-alert') . '</p>';
    }
    
    /**
     * 渲染邮箱字段
     */
    public function render_email_field() {
        $value = get_option('dsa_admin_email', get_option('admin_email'));
        echo '<input type="email" name="dsa_admin_email" value="' . esc_attr($value) . '" class="regular-text">';
        echo '<p class="description">' . __('接收库存预警通知的邮箱地址,多个邮箱用逗号分隔', 'dynamic-stock-alert') . '</p>';
    }
    
    /**
     * 渲染邮件主题字段
     */
    public function render_subject_field() {
        $value = get_option('dsa_email_subject', '库存预警通知');
        echo '<input type="text" name="dsa_email_subject" value="' . esc_attr($value) . '" class="regular-text">';
    }
    
    /**
     * 渲染频率字段
     */
    public function render_frequency_field() {
        $value = get_option('dsa_email_frequency', 'daily');
        ?>
        <select name="dsa_email_frequency">
            <option value="hourly" <?php selected($value, 'hourly'); ?>><?php _e('每小时', 'dynamic-stock-alert'); ?></option>
            <option value="daily" <?php selected($value, 'daily'); ?>><?php _e('每天', 'dynamic-stock-alert'); ?></option>
            <option value="twicedaily" <?php selected($value, 'twicedaily'); ?>><?php _e('每天两次', 'dynamic-stock-alert'); ?></option>
        </select>
        <?php
    }
    
    /**
     * 渲染预警状态
     */
    public function render_alert_status() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'stock_alert_logs';
        
        // 获取最近7天的预警记录
        $alerts = $wpdb->get_results("
            SELECT * FROM $table_name 
            WHERE alert_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)
            ORDER BY alert_date DESC
            LIMIT 20
        ");
        
        if (empty($alerts)) {
            echo '<p>' . __('最近7天内没有库存预警记录。', 'dynamic-stock-alert') . '</p>';
            return;
        }
        
        echo '<table class="wp-list-table widefat fixed striped">';
        echo '<thead><tr>
                <th>' . __('商品ID', 'dynamic-stock-alert') . '</th>
                <th>' . __('商品名称', 'dynamic-stock-alert') . '</th>
                <th>' . __('当前库存', 'dynamic-stock-alert') . '</th>
                <th>' . __('预警阈值', 'dynamic-stock-alert') . '</th>
                <th>' . __('预警时间', 'dynamic-stock-alert') . '</th>
                <th>' . __('通知状态', 'dynamic-stock-alert') . '</th>
              </tr></thead>';
        echo '<tbody>';
        
        foreach ($alerts as $alert) {
            $product = wc_get_product($alert->product_id);
            $product_name = $product ? $product->get_name() : __('商品已删除', 'dynamic-stock-alert');
            
            echo '<tr>';
            echo '<td>' . $alert->product_id . '</td>';
            echo '<td>' . esc_html($product_name) . '</td>';
            echo '<td>' . $alert->current_stock . '</td>';
            echo '<td>' . $alert->threshold . '</td>';
            echo '<td>' . $alert->alert_date . '</td>';
            echo '<td>' . ($alert->notified ? __('已通知', 'dynamic-stock-alert') : __('未通知', 'dynamic-stock-alert')) . '</td>';
            echo '</tr>';
        }
        
        echo '</tbody></table>';
    }
    
    /**
     * 加载后台资源
     */
    public function enqueue_admin_assets($hook) {
        if (strpos($hook, 'dsa-settings') !== false || $hook === 'edit.php') {
            wp_enqueue_style('dsa-admin-style', DSA_PLUGIN_URL . 'assets/css/admin-style.css', array(), DSA_VERSION);
            wp_enqueue_script('dsa-admin-script', DSA_PLUGIN_URL . 'assets/js/admin-script.js', array('jquery'), DSA_VERSION, true);
        }
    }
}

库存监控类实现

创建includes/class-stock-monitor.php文件:

<?php
/**
 * 库存监控类
 */
class DSA_Stock_Monitor {
    
    public function __construct() {
        // 监控库存变化
        add_action('woocommerce_product_set_stock', array($this, 'check_stock_level'), 10, 1);
        add_action('woocommerce_variation_set_stock', array($this, 'check_stock_level'), 10, 1);
        
        // 设置定时任务
        add_action('init', array($this, 'setup_scheduled_events'));
        add_action('dsa_daily_stock_check', array($this, 'scheduled_stock_check'));
    }
    
    /**
     * 检查库存水平
     */
    public function check_stock_level($product) {
        $product_id = $product->get_id();
        $current_stock = $product->get_stock_quantity();
        
        // 获取预警阈值
        $threshold = get_post_meta($product_id, '_stock_alert_threshold', true);
        if (empty($threshold)) {
            $threshold = get_option('dsa_default_threshold', 10);
        }
        
        // 如果库存低于阈值且大于0(0表示缺货,可能不需要预警)
        if ($current_stock > 0 && $current_stock <= $threshold) {
            $this->log_stock_alert($product_id, $product->get_name(), $current_stock, $threshold);
        }
    }
    
    /**
     * 记录库存预警
     */
    private function log_stock_alert($product_id, $product_name, $current_stock, $threshold) {
        global $wpdb;

$table_name = $wpdb->prefix . 'stock_alert_logs';

    
    // 检查是否已有未处理的相同预警
    $existing_alert = $wpdb->get_var($wpdb->prepare(
        "SELECT id FROM $table_name 
        WHERE product_id = %d 
        AND notified = 0 
        AND DATE(alert_date) = CURDATE()",
        $product_id
    ));
    
    if (!$existing_alert) {
        $wpdb->insert(
            $table_name,
            array(
                'product_id' => $product_id,
                'product_name' => $product_name,
                'current_stock' => $current_stock,
                'threshold' => $threshold,
                'notified' => 0
            ),
            array('%d', '%s', '%d', '%d', '%d')
        );
    }
}

/**
 * 设置定时任务
 */
public function setup_scheduled_events() {
    $frequency = get_option('dsa_email_frequency', 'daily');
    
    if (!wp_next_scheduled('dsa_daily_stock_check')) {
        wp_schedule_event(time(), $frequency, 'dsa_daily_stock_check');
    }
}

/**
 * 定时库存检查
 */
public function scheduled_stock_check() {
    global $wpdb;
    
    // 获取所有需要监控的商品
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key' => '_manage_stock',
                'value' => 'yes'
            )
        )
    );
    
    $products = get_posts($args);
    
    foreach ($products as $product_post) {
        $product = wc_get_product($product_post->ID);
        
        if ($product && $product->managing_stock()) {
            $this->check_stock_level($product);
        }
    }
}

/**
 * 获取需要预警的商品列表
 */
public function get_alert_products() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'stock_alert_logs';
    
    return $wpdb->get_results("
        SELECT DISTINCT product_id, product_name, current_stock, threshold 
        FROM $table_name 
        WHERE notified = 0 
        AND alert_date >= DATE_SUB(NOW(), INTERVAL 1 DAY)
        ORDER BY current_stock ASC
    ");
}

}


## 邮件通知类实现

创建`includes/class-email-notifier.php`文件:

<?php
/**

  • 邮件通知类
    */

class DSA_Email_Notifier {


public function __construct() {
    // 挂钩到库存检查事件
    add_action('dsa_daily_stock_check', array($this, 'send_alert_emails'));
    
    // 添加手动发送测试邮件的功能
    add_action('admin_post_dsa_send_test_email', array($this, 'send_test_email'));
}

/**
 * 发送预警邮件
 */
public function send_alert_emails() {
    $stock_monitor = new DSA_Stock_Monitor();
    $alert_products = $stock_monitor->get_alert_products();
    
    if (empty($alert_products)) {
        return;
    }
    
    $admin_emails = get_option('dsa_admin_email', get_option('admin_email'));
    $email_subject = get_option('dsa_email_subject', '库存预警通知');
    
    // 构建邮件内容
    $message = $this->build_email_content($alert_products);
    
    // 发送邮件
    $headers = array('Content-Type: text/html; charset=UTF-8');
    $email_sent = wp_mail($admin_emails, $email_subject, $message, $headers);
    
    // 如果邮件发送成功,更新通知状态
    if ($email_sent) {
        $this->update_notification_status($alert_products);
    }
}

/**
 * 构建邮件内容
 */
private function build_email_content($alert_products) {
    $site_name = get_bloginfo('name');
    $current_date = date('Y年m月d日 H:i:s');
    
    $html = '<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>库存预警通知</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background-color: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
            .product-table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
            .product-table th, .product-table td { border: 1px solid #ddd; padding: 12px; text-align: left; }
            .product-table th { background-color: #f2f2f2; }
            .low-stock { background-color: #fff3cd; }
            .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; font-size: 12px; color: #666; }
            .btn { display: inline-block; padding: 10px 20px; background-color: #0073aa; color: white; text-decoration: none; border-radius: 3px; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h2>⚠️ 库存预警通知</h2>
                <p>以下商品库存已达到预警阈值,请及时补货。</p>
            </div>
            
            <p>网站: <strong>' . esc_html($site_name) . '</strong></p>
            <p>检查时间: ' . $current_date . '</p>
            
            <table class="product-table">
                <thead>
                    <tr>
                        <th>商品ID</th>
                        <th>商品名称</th>
                        <th>当前库存</th>
                        <th>预警阈值</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>';
    
    foreach ($alert_products as $product) {
        $product_url = admin_url('post.php?post=' . $product->product_id . '&action=edit');
        $stock_status = $product->current_stock <= 3 ? 'danger' : 'warning';
        
        $html .= '<tr class="low-stock">
            <td>' . $product->product_id . '</td>
            <td>' . esc_html($product->product_name) . '</td>
            <td><strong style="color: #dc3545;">' . $product->current_stock . '</strong></td>
            <td>' . $product->threshold . '</td>
            <td><a href="' . $product_url . '" class="btn">管理库存</a></td>
        </tr>';
    }
    
    $admin_url = admin_url('admin.php?page=dsa-settings');
    $html .= '</tbody>
            </table>
            
            <p>请登录网站后台处理库存预警:</p>
            <p><a href="' . $admin_url . '" class="btn">查看库存预警面板</a></p>
            
            <div class="footer">
                <p>此邮件由小批量动态库存预警插件自动发送</p>
                <p>您可以在插件设置中调整通知频率和接收邮箱</p>
            </div>
        </div>
    </body>
    </html>';
    
    return $html;
}

/**
 * 更新通知状态
 */
private function update_notification_status($alert_products) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'stock_alert_logs';
    
    $product_ids = array_map(function($product) {
        return $product->product_id;
    }, $alert_products);
    
    if (!empty($product_ids)) {
        $placeholders = implode(',', array_fill(0, count($product_ids), '%d'));
        $wpdb->query($wpdb->prepare(
            "UPDATE $table_name SET notified = 1 WHERE product_id IN ($placeholders)",
            $product_ids
        ));
    }
}

/**
 * 发送测试邮件
 */
public function send_test_email() {
    if (!current_user_can('manage_options')) {
        wp_die('权限不足');
    }
    
    // 创建测试数据
    $test_products = array(
        (object) array(
            'product_id' => 1,
            'product_name' => '测试商品A',
            'current_stock' => 5,
            'threshold' => 10
        ),
        (object) array(
            'product_id' => 2,
            'product_name' => '测试商品B',
            'current_stock' => 3,
            'threshold' => 15
        )
    );
    
    $admin_email = get_option('admin_email');
    $message = $this->build_email_content($test_products);
    $subject = '库存预警测试邮件 - ' . get_bloginfo('name');
    
    $sent = wp_mail($admin_email, $subject, $message, array('Content-Type: text/html; charset=UTF-8'));
    
    if ($sent) {
        wp_redirect(admin_url('admin.php?page=dsa-settings&test=success'));
    } else {
        wp_redirect(admin_url('admin.php?page=dsa-settings&test=failed'));
    }
    exit;
}

}


## 前端资源文件

创建`assets/css/admin-style.css`:

/ 库存预警插件后台样式 /

.dsa-dashboard {

margin-top: 30px;
background: #fff;
padding: 20px;
border: 1px solid #ccd0d4;
box-shadow: 0 1px 1px rgba(0,0,0,.04);

}

.dsa-dashboard h2 {

margin-top: 0;
padding-bottom: 10px;
border-bottom: 1px solid #eee;

}

.dsa-stats {

display: flex;
gap: 20px;
margin-bottom: 20px;

}

.dsa-stat-box {

flex: 1;
background: #f8f9fa;
padding: 15px;
border-radius: 4px;
border-left: 4px solid #0073aa;

}

.dsa-stat-box h3 {

margin: 0 0 10px 0;
font-size: 14px;
color: #666;

}

.dsa-stat-box .stat-number {

font-size: 24px;
font-weight: bold;
color: #0073aa;

}

.dsa-test-button {

margin-top: 20px;

}

.dsa-test-button .button {

background: #28a745;
border-color: #28a745;
color: white;

}

.dsa-test-button .button:hover {

background: #218838;
border-color: #1e7e34;

}

/ 商品列表页面样式 /
.column-stock_alert {

width: 100px;

}

.stock-alert-indicator {

display: inline-block;
padding: 3px 8px;
border-radius: 3px;
font-size: 12px;
font-weight: bold;

}

.stock-alert-low {

background: #f8d7da;
color: #721c24;

}

.stock-alert-ok {

background: #d4edda;
color: #155724;

}


创建`assets/js/admin-script.js`:

/**

  • 库存预警插件后台脚本
    */

jQuery(document).ready(function($) {


// 批量编辑功能增强
$(document).on('click', '#doaction, #doaction2', function(e) {
    var action = $(this).prev('select').val();
    if (action === 'edit') {
        setTimeout(function() {
            $('.inline-edit-group input[name="_bulk_stock_alert_threshold"]').focus();
        }, 100);
    }
});

// 测试邮件发送
$('#dsa-send-test-email').on('click', function(e) {
    e.preventDefault();
    
    if (!confirm('确定要发送测试邮件吗?')) {
        return;
    }
    
    var $button = $(this);
    var originalText = $button.text();
    
    $button.text('发送中...').prop('disabled', true);
    
    $.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'dsa_send_test_email',
            nonce: dsa_admin.nonce
        },
        success: function(response) {
            if (response.success) {
                alert('测试邮件发送成功!');
            } else {
                alert('发送失败:' + response.data);
            }
        },
        error: function() {
            alert('请求失败,请检查网络连接');
        },
        complete: function() {
            $button.text(originalText).prop('disabled', false);
        }
    });
});

// 实时库存监控
if (typeof wp.hooks !== 'undefined') {
    wp.hooks.addAction('woocommerce_inventory_panel_after', 'dsa', function(product) {
        var stock = product.get('stock_quantity');
        var threshold = product.get('meta_data').find(function(meta) {
            return meta.key === '_stock_alert_threshold';
        });
        
        threshold = threshold ? threshold.value : dsa_admin.default_threshold;
        
        if (stock > 0 && stock <= threshold) {
            $('.woocommerce-product-data')
                .find('.stock-alert-notice')
                .remove()
                .end()
                .prepend(
                    '<div class="notice notice-warning stock-alert-notice">' +
                    '<p>⚠️ 当前库存(' + stock + ')已低于预警阈值(' + threshold + ')</p>' +
                    '</div>'
                );
        }
    });
}

});


## 卸载清理脚本

创建`uninstall.php`文件:

<?php
/**

  • 插件卸载脚本
    */

// 防止直接访问
if (!defined('WP_UNINSTALL_PLUGIN')) {

exit;

}

// 清理选项
delete_option('dsa_default_threshold');
delete_option('dsa_admin_email');
delete_option('dsa_email_subject');
delete_option('dsa_email_frequency');

// 清理商品元数据
global $wpdb;
$wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_key = '_stock_alert_threshold'");

// 删除数据库表
$table_name = $wpdb->prefix . 'stock_alert_logs';
$wpdb->query("DROP TABLE IF EXISTS $table_name");

// 清理定时任务
wp_clear_scheduled_hook('dsa_daily_stock_check');


## 插件使用说明

### 安装与激活

1. 将插件文件夹上传到 `/wp-content/plugins/` 目录
2. 在WordPress后台激活插件
3. 确保WooCommerce插件已安装并激活

### 配置步骤

1. **设置全局阈值**:进入 WooCommerce → 库存预警 → 设置默认预警阈值
2. **商品级设置**:编辑单个商品时,在库存选项卡中设置特定阈值
3. **批量设置**:在商品列表页面使用批量编辑功能
4. **通知配置**:设置接收邮箱、邮件主题和检查频率

### 功能特点

1. **智能监控**:实时监控库存变化,自动触发预警
2. **灵活阈值**:支持全局默认值和商品特定值
3. **批量管理**:支持批量设置和查看预警状态
4. **详细日志**:记录所有预警事件,便于分析
5. **邮件通知**:美观的HTML邮件模板,包含直接管理链接

### 扩展建议

您可以根据需要扩展以下功能:

1. **短信通知**:集成短信网关发送预警短信
2. **多仓库支持**:为不同仓库设置不同的预警规则
3. **销售预测**:基于历史销售数据智能调整阈值
4. **供应商通知**:库存不足时自动通知供应商
5. **REST API**:提供API接口供外部系统调用

## 总结

通过本教程,您已经成功开发了一个功能完整的小批量动态库存预警WordPress插件。该插件不仅解决了电商网站库存监控的基本需求,还提供了灵活的配置选项和友好的用户界面。您可以根据实际业务需求进一步扩展功能,或优化现有代码以提高性能。
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5843.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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