文章目录
-
- 在当今电子商务环境中,动态定价策略已成为提升竞争力的关键手段。对于使用WordPress的商家来说,实现智能报价与动态定价功能可以显著提高销售转化率和利润率。本教程将指导您开发一个轻量级WordPress插件,实现小批量定制产品的智能报价与动态定价功能。
- 我们的插件将实现以下核心功能: 根据产品数量自动计算折扣 考虑用户类型(新客户、VIP客户等)提供差异化定价 基于时间因素的动态定价(促销时段、季节性调整) 实时报价显示与更新 与WooCommerce的无缝集成
- 首先,我们创建插件的基本文件结构: smart-pricing-plugin/ ├── smart-pricing.php # 主插件文件 ├── includes/ │ ├── class-pricing-engine.php │ ├── class-ajax-handler.php │ └── class-admin-settings.php ├── assets/ │ ├── css/ │ │ └── frontend.css │ └── js/ │ └── frontend.js └── templates/ └── pricing-display.php
- <?php /** * Plugin Name: 智能报价与动态定价插件 * Plugin URI: https://yourwebsite.com/ * Description: 为WordPress网站提供小批量定制产品的智能报价与动态定价功能 * Version: 1.0.0 * Author: 您的名称 * License: GPL v2 or later * Text Domain: smart-pricing */ // 防止直接访问 if (!defined('ABSPATH')) { exit; } // 定义插件常量 define('SMART_PRICING_VERSION', '1.0.0'); define('SMART_PRICING_PLUGIN_DIR', plugin_dir_path(__FILE__)); define('SMART_PRICING_PLUGIN_URL', plugin_dir_url(__FILE__)); // 自动加载类文件 spl_autoload_register(function ($class_name) { if (strpos($class_name, 'SmartPricing_') === 0) { $file = SMART_PRICING_PLUGIN_DIR . 'includes/class-' . strtolower(str_replace('_', '-', $class_name)) . '.php'; if (file_exists($file)) { require_once $file; } } }); // 初始化插件 function smart_pricing_init() { // 检查WooCommerce是否激活 if (!class_exists('WooCommerce')) { add_action('admin_notices', function() { echo '<div class="notice notice-error"><p>智能报价插件需要WooCommerce支持,请先安装并激活WooCommerce插件。</p></div>'; }); return; } // 初始化核心类 SmartPricing_Pricing_Engine::get_instance(); SmartPricing_Ajax_Handler::get_instance(); if (is_admin()) { SmartPricing_Admin_Settings::get_instance(); } } add_action('plugins_loaded', 'smart_pricing_init'); // 激活插件时的操作 register_activation_hook(__FILE__, 'smart_pricing_activate'); function smart_pricing_activate() { // 创建必要的数据库表 global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = $wpdb->prefix . 'smart_pricing_rules'; $sql = "CREATE TABLE IF NOT EXISTS $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, rule_name varchar(100) NOT NULL, min_quantity int NOT NULL DEFAULT 0, max_quantity int NOT NULL DEFAULT 9999, discount_type enum('percentage','fixed') DEFAULT 'percentage', discount_value decimal(10,2) NOT NULL, user_role varchar(50) DEFAULT '', start_date datetime DEFAULT NULL, end_date datetime DEFAULT NULL, is_active tinyint(1) DEFAULT 1, PRIMARY KEY (id) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); // 添加默认定价规则 $default_rules = array( array( 'rule_name' => '小批量折扣', 'min_quantity' => 10, 'max_quantity' => 50, 'discount_type' => 'percentage', 'discount_value' => 5.00, 'user_role' => '', ), array( 'rule_name' => '中批量折扣', 'min_quantity' => 51, 'max_quantity' => 200, 'discount_type' => 'percentage', 'discount_value' => 10.00, 'user_role' => '', ), array( 'rule_name' => 'VIP客户折扣', 'min_quantity' => 1, 'max_quantity' => 9999, 'discount_type' => 'percentage', 'discount_value' => 15.00, 'user_role' => 'vip_customer', ), ); foreach ($default_rules as $rule) { $wpdb->insert($table_name, $rule); } } ?>
- <?php /** * 智能定价引擎类 * 负责计算动态价格和折扣 */ class SmartPricing_Pricing_Engine { private static $instance = null; private $pricing_rules = array(); public static function get_instance() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } private function __construct() { $this->load_pricing_rules(); add_filter('woocommerce_product_get_price', array($this, 'calculate_dynamic_price'), 10, 2); add_filter('woocommerce_product_variation_get_price', array($this, 'calculate_dynamic_price'), 10, 2); add_action('woocommerce_before_calculate_totals', array($this, 'apply_cart_discounts')); } /** * 从数据库加载定价规则 */ private function load_pricing_rules() { global $wpdb; $table_name = $wpdb->prefix . 'smart_pricing_rules'; $this->pricing_rules = $wpdb->get_results( "SELECT * FROM $table_name WHERE is_active = 1", ARRAY_A ); } /** * 计算动态价格 * @param float $price 原始价格 * @param WC_Product $product 产品对象 * @return float 计算后的价格 */ public function calculate_dynamic_price($price, $product) { // 只在特定页面应用动态定价 if (is_admin() && !defined('DOING_AJAX')) { return $price; } // 获取当前用户信息 $user_id = get_current_user_id(); $user_roles = $user_id ? wp_get_current_user()->roles : array('guest'); // 获取产品数量(从购物车或通过AJAX传递) $quantity = $this->get_product_quantity($product->get_id()); // 应用定价规则 $adjusted_price = $this->apply_pricing_rules($price, $quantity, $user_roles); return max($adjusted_price, 0); // 确保价格不为负 } /** * 获取产品数量 * @param int $product_id 产品ID * @return int 产品数量 */ private function get_product_quantity($product_id) { $quantity = 1; // 默认数量 // 从购物车获取数量 if (WC()->cart && !WC()->cart->is_empty()) { foreach (WC()->cart->get_cart() as $cart_item) { if ($cart_item['product_id'] == $product_id) { $quantity = $cart_item['quantity']; break; } } } // 允许通过AJAX覆盖数量 if (defined('DOING_AJAX') && DOING_AJAX && isset($_POST['quantity'])) { $quantity = intval($_POST['quantity']); } return $quantity; } /** * 应用定价规则 * @param float $base_price 基础价格 * @param int $quantity 数量 * @param array $user_roles 用户角色 * @return float 调整后的价格 */ private function apply_pricing_rules($base_price, $quantity, $user_roles) { $best_price = $base_price; $current_time = current_time('mysql'); foreach ($this->pricing_rules as $rule) { // 检查数量范围 if ($quantity < $rule['min_quantity'] || $quantity > $rule['max_quantity']) { continue; } // 检查用户角色 if (!empty($rule['user_role']) && !in_array($rule['user_role'], $user_roles)) { continue; } // 检查时间有效性 if ($rule['start_date'] && $rule['start_date'] > $current_time) { continue; } if ($rule['end_date'] && $rule['end_date'] < $current_time) { continue; } // 计算折扣价格 $discounted_price = $this->calculate_discount($base_price, $rule); // 选择最优价格(最低价格) if ($discounted_price < $best_price) { $best_price = $discounted_price; } } return $best_price; } /** * 计算折扣 * @param float $price 原始价格 * @param array $rule 定价规则 * @return float 折扣后价格 */ private function calculate_discount($price, $rule) { if ($rule['discount_type'] == 'percentage') { $discount = $price * ($rule['discount_value'] / 100); return $price - $discount; } else { return max($price - $rule['discount_value'], 0); } } /** * 应用购物车折扣 * @param WC_Cart $cart 购物车对象 */ public function apply_cart_discounts($cart) { if (is_admin() && !defined('DOING_AJAX')) { return; } // 这里可以添加购物车级别的折扣逻辑 // 例如:基于总金额的折扣或组合产品折扣 } } ?>
- <?php /** * AJAX请求处理器 * 处理前端实时报价请求 */ class SmartPricing_Ajax_Handler { private static $instance = null; public static function get_instance() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } private function __construct() { add_action('wp_ajax_get_dynamic_price', array($this, 'get_dynamic_price_ajax')); add_action('wp_ajax_nopriv_get_dynamic_price', array($this, 'get_dynamic_price_ajax')); } /** * 处理动态价格AJAX请求 */ public function get_dynamic_price_ajax() { // 验证nonce if (!check_ajax_referer('smart_pricing_nonce', 'security', false)) { wp_die('安全验证失败'); } // 获取请求参数 $product_id = intval($_POST['product_id']); $quantity = intval($_POST['quantity']); // 验证参数 if ($product_id <= 0 || $quantity <= 0) { wp_send_json_error('参数无效'); } // 获取产品 $product = wc_get_product($product_id); if (!$product) { wp_send_json_error('产品不存在'); } // 获取基础价格 $base_price = $product->get_price(); // 创建临时定价引擎实例 $pricing_engine = SmartPricing_Pricing_Engine::get_instance(); // 使用反射调用私有方法(实际应用中应优化此部分) $reflection = new ReflectionClass($pricing_engine); $method = $reflection->getMethod('apply_pricing_rules'); $method->setAccessible(true); // 获取用户角色 $user_id = get_current_user_id(); $user_roles = $user_id ? wp_get_current_user()->roles : array('guest'); // 计算动态价格 $dynamic_price = $method->invoke($pricing_engine, $base_price, $quantity, $user_roles); // 计算节省金额 $savings = $base_price * $quantity - $dynamic_price * $quantity; // 准备响应数据 $response = array( 'success' => true, 'data' => array( 'base_price' => wc_price($base_price), 'dynamic_price' => wc_price($dynamic_price), 'total_base' => wc_price($base_price * $quantity), 'total_dynamic' => wc_price($dynamic_price * $quantity), 'savings' => wc_price($savings), 'savings_percentage' => $base_price > 0 ? round(($savings / ($base_price * $quantity)) * 100, 2) : 0, 'quantity' => $quantity, ), ); wp_send_json($response); } } ?>
- /** * 前端动态报价交互 */ jQuery(document).ready(function($) { // 初始化报价计算器 function initPricingCalculator() { $('.smart-pricing-calculator').each(function() { var $calculator = $(this); var productId = $calculator.data('product-id'); var basePrice = $calculator.data('base-price'); // 创建数量输入 var $quantityInput = $('<input>', { type: 'number', min: 1, value: 1, class: 'pricing-quantity' }); // 创建计算按钮 var $calculateBtn = $('<button>', { text: '计算报价', class: 'button pricing-calculate-btn' }); // 创建结果显示区域 var $results = $('<div>', { class: 'pricing-results', html: '<div class="price-breakdown"></div>' }); // 组装计算器 $calculator.append( $('<div class="quantity-selector">').append( $('<label>').text('数量: '), $quantityInput ), $calculateBtn, $results ); // 绑定计算事件 $calculateBtn.on('click', function() { calculateDynamicPrice(productId, $quantityInput.val(), $results); }); // 实时计算(输入时自动计算) $quantityInput.on('input', function() { calculateDynamicPrice(productId, $(this).val(), $results); }); // 初始计算 calculateDynamicPrice(productId, 1, $results); }); } // 计算动态价格 function calculateDynamicPrice(productId, quantity, $resultsContainer) { if (!productId || quantity < 1) { return; } // 显示加载状态 $resultsContainer.find('.price-breakdown').html('<div class="loading">计算中...</div>'); // 发送AJAX请求 $.ajax({ url: smartPricing.ajax_url, type: 'POST', data: { action: 'get_dynamic_price', product_id: productId, quantity: quantity, security: smartPricing.nonce }, success: function(response) { if (response.success) { var data = response.data; var html = ` <div class="price-summary"> <h4>报价详情</h4> <table class="price-table"> <tr> <td>单价:</td> <td>${data.base_price} → <strong>${data.dynamic_price}</strong></td> </tr> <tr> <td>${quantity}件总价:</td> <td>${data.total_base} → <strong>${data.total_dynamic}</strong></td> </tr> <tr class="savings-row"> <td>节省金额:</td> <td class="savings-amount">${data.savings} (${data.savings_percentage}%)</td> </tr> </table> </div> `; $resultsContainer.find('.price-breakdown').html(html); } else { $resultsContainer.find('.price-breakdown').html('<div class="error">计算失败,请重试</div>'); } }, error: function() { $resultsContainer.find('.price-breakdown').html('<div class="error">网络错误,请刷新页面</div>'); } }); } // 初始化 initPricingCalculator(); // 添加到购物车时更新价格显示 $(document).on('found_variation', function(event, variation) { // 当产品变体选择时更新价格计算器 setTimeout(initPricingCalculator, 100); }); });
- <?php /** * 管理设置类 * 提供定价规则管理界面 */ class SmartPricing_Admin_Settings { private static $instance = null; public static function get_instance() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } private function __construct() { add_action('admin_menu', array($this, 'add_admin_menu')); add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts')); add_action('admin_init', array($this, 'register_settings')); } /** * 添加管理菜单 */ public function add_admin_menu() { add_submenu_page( 'woocommerce', '智能定价设置', '智能定价', 'manage_options', 'smart-pricing-settings', array($this, 'render_settings_page') ); } /** * 加载管理端脚本和样式 */ public function enqueue_admin_scripts($hook) { if ('woocommerce_page_smart-pricing-settings' !== $hook) { return; } wp_enqueue_style( 'smart-pricing-admin', SMART_PRICING_PLUGIN_URL . 'assets/css/admin.css', array(), SMART_PRICING_VERSION ); wp_enqueue_script( 'smart-pricing-admin', SMART_PRICING_PLUGIN_URL . 'assets/js/admin.js', array('jquery', 'jquery-ui-datepicker'), SMART_PRICING_VERSION, true ); wp_localize_script('smart-pricing-admin', 'smartPricingAdmin', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('smart_pricing_admin_nonce'), 'confirm_delete' => __('确定要删除这条规则吗?', 'smart-pricing'), )); } /** * 注册设置选项 */ public function register_settings() { register_setting('smart_pricing_settings', 'smart_pricing_options'); add_settings_section( 'smart_pricing_main', '定价规则管理', array($this, 'render_section_callback'), 'smart-pricing-settings' ); } /** * 渲染设置页面 */ public function render_settings_page() { if (!current_user_can('manage_options')) { wp_die('权限不足'); } // 处理表单提交 $this->handle_form_submissions(); // 获取所有定价规则 global $wpdb; $table_name = $wpdb->prefix . 'smart_pricing_rules'; $rules = $wpdb->get_results("SELECT * FROM $table_name ORDER BY min_quantity ASC", ARRAY_A); // 获取用户角色 $user_roles = get_editable_roles(); ?> <div class="wrap smart-pricing-settings"> <h1><?php echo esc_html(get_admin_page_title()); ?></h1> <div class="notice notice-info"> <p>在此管理智能定价规则。规则按优先级从上到下应用,匹配的第一个规则将被使用。</p> </div> <!-- 添加新规则表单 --> <div class="card"> <h2>添加新定价规则</h2> <form method="post" action=""> <?php wp_nonce_field('smart_pricing_add_rule', 'smart_pricing_nonce'); ?> <input type="hidden" name="action" value="add_rule"> <table class="form-table"> <tr> <th scope="row"><label for="rule_name">规则名称</label></th> <td> <input type="text" id="rule_name" name="rule_name" class="regular-text" required> </td> </tr> <tr> <th scope="row"><label for="min_quantity">最小数量</label></th> <td> <input type="number" id="min_quantity" name="min_quantity" min="0" value="0" class="small-text" required> </td> </tr> <tr> <th scope="row"><label for="max_quantity">最大数量</label></th> <td> <input type="number" id="max_quantity" name="max_quantity" min="1" value="9999" class="small-text" required> <p class="description">设置为9999表示无上限</p> </td> </tr> <tr> <th scope="row"><label>折扣类型</label></th> <td> <label> <input type="radio" name="discount_type" value="percentage" checked> 百分比折扣 </label> <label style="margin-left: 20px;"> <input type="radio" name="discount_type" value="fixed"> 固定金额折扣 </label> </td> </tr> <tr> <th scope="row"><label for="discount_value">折扣值</label></th> <td> <input type="number" id="discount_value" name="discount_value" step="0.01" min="0" class="small-text" required> <span class="discount-unit">%</span> </td> </tr> <tr> <th scope="row"><label for="user_role">适用用户角色</label></th> <td> <select id="user_role" name="user_role"> <option value="">所有用户</option> <?php foreach ($user_roles as $role => $details): ?> <option value="<?php echo esc_attr($role); ?>"> <?php echo esc_html($details['name']); ?> </option> <?php endforeach; ?> </select> <p class="description">留空表示适用于所有用户</p> </td> </tr> <tr> <th scope="row"><label for="start_date">生效时间</label></th> <td> <input type="text" id="start_date" name="start_date" class="datepicker" placeholder="YYYY-MM-DD"> <p class="description">留空表示立即生效</p> </td> </tr> <tr> <th scope="row"><label for="end_date">结束时间</label></th> <td> <input type="text" id="end_date" name="end_date" class="datepicker" placeholder="YYYY-MM-DD"> <p class="description">留空表示永久有效</p> </td> </tr> </table> <?php submit_button('添加规则', 'primary', 'submit_rule'); ?> </form> </div> <!-- 现有规则列表 --> <div class="card"> <h2>现有定价规则</h2> <?php if (empty($rules)): ?> <p>暂无定价规则。</p> <?php else: ?> <table class="wp-list-table widefat fixed striped"> <thead> <tr> <th>规则名称</th> <th>数量范围</th> <th>折扣</th> <th>适用角色</th> <th>生效时间</th> <th>状态</th> <th>操作</th> </tr> </thead> <tbody> <?php foreach ($rules as $rule): ?> <tr> <td><?php echo esc_html($rule['rule_name']); ?></td> <td> <?php echo esc_html($rule['min_quantity']); echo ' - '; echo $rule['max_quantity'] == 9999 ? '∞' : esc_html($rule['max_quantity']); ?> </td> <td> <?php if ($rule['discount_type'] == 'percentage') { echo esc_html($rule['discount_value']) . '%'; } else { echo '¥' . esc_html($rule['discount_value']); } ?> </td> <td> <?php echo empty($rule['user_role']) ? '所有用户' : esc_html($rule['user_role']); ?> </td> <td> <?php $dates = array(); if ($rule['start_date']) { $dates[] = date('Y-m-d', strtotime($rule['start_date'])); } if ($rule['end_date']) { $dates[] = date('Y-m-d', strtotime($rule['end_date'])); } echo $dates ? implode(' 至 ', $dates) : '永久'; ?> </td> <td> <?php if ($rule['is_active']): ?> <span class="status-active">启用</span> <?php else: ?> <span class="status-inactive">禁用</span> <?php endif; ?> </td> <td> <form method="post" action="" style="display: inline;"> <?php wp_nonce_field('smart_pricing_toggle_rule', 'smart_pricing_nonce'); ?> <input type="hidden" name="action" value="toggle_rule"> <input type="hidden" name="rule_id" value="<?php echo esc_attr($rule['id']); ?>"> <button type="submit" class="button button-small"> <?php echo $rule['is_active'] ? '禁用' : '启用'; ?> </button> </form> <form method="post" action="" style="display: inline;"> <?php wp_nonce_field('smart_pricing_delete_rule', 'smart_pricing_nonce'); ?> <input type="hidden" name="action" value="delete_rule"> <input type="hidden" name="rule_id" value="<?php echo esc_attr($rule['id']); ?>"> <button type="submit" class="button button-small button-delete" onclick="return confirm('确定要删除这条规则吗?');"> 删除 </button> </form> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif; ?> </div> <!-- 批量定价工具 --> <div class="card"> <h2>批量定价工具</h2> <form method="post" action=""> <?php wp_nonce_field('smart_pricing_bulk_update', 'smart_pricing_nonce'); ?> <input type="hidden" name="action" value="bulk_update"> <table class="form-table"> <tr> <th scope="row"><label>应用范围</label></th> <td> <select name="product_scope"> <option value="all">所有产品</option> <option value="category">特定分类</option> <option value="selected">选定产品</option> </select> </td> </tr> <tr> <th scope="row"><label>定价规则</label></th> <td> <select name="pricing_rule"> <option value="">-- 选择规则 --</option> <?php foreach ($rules as $rule): ?> <?php if ($rule['is_active']): ?> <option value="<?php echo esc_attr($rule['id']); ?>"> <?php echo esc_html($rule['rule_name']); ?> </option> <?php endif; ?> <?php endforeach; ?> </select> </td> </tr> </table> <?php submit_button('应用批量定价', 'secondary', 'submit_bulk'); ?> </form> </div> </div> <script> jQuery(document).ready(function($) { // 日期选择器 $('.datepicker').datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true }); // 折扣类型切换 $('input[name="discount_type"]').change(function() { var unit = $(this).val() === 'percentage' ? '%' : '¥'; $('.discount-unit').text(unit); }); }); </script> <?php } /** * 处理表单提交 */ private function handle_form_submissions() { if (!isset($_POST['action'])) { return; } // 验证nonce if (!isset($_POST['smart_pricing_nonce']) || !wp_verify_nonce($_POST['smart_pricing_nonce'], 'smart_pricing_' . $_POST['action'])) { wp_die('安全验证失败'); } global $wpdb; $table_name = $wpdb->prefix . 'smart_pricing_rules'; switch ($_POST['action']) { case 'add_rule': $data = array( 'rule_name' => sanitize_text_field($_POST['rule_name']), 'min_quantity' => intval($_POST['min_quantity']), 'max_quantity' => intval($_POST['max_quantity']), 'discount_type' => sanitize_text_field($_POST['discount_type']), 'discount_value' => floatval($_POST['discount_value']), 'user_role' => sanitize_text_field($_POST['user_role']), 'start_date' => !empty($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) . ' 00:00:00' : null, 'end_date' => !empty($_POST['end_date']) ? sanitize_text_field($_POST['end_date']) . ' 23:59:59' : null, 'is_active' => 1, ); $wpdb->insert($table_name, $data); echo '<div class="notice notice-success"><p>规则添加成功!</p></div>'; break; case 'toggle_rule': $rule_id = intval($_POST['rule_id']); $current_status = $wpdb->get_var( $wpdb->prepare("SELECT is_active FROM $table_name WHERE id = %d", $rule_id) ); $wpdb->update( $table_name, array('is_active' => $current_status ? 0 : 1), array('id' => $rule_id) ); echo '<div class="notice notice-success"><p>规则状态已更新!</p></div>'; break; case 'delete_rule': $rule_id = intval($_POST['rule_id']); $wpdb->delete($table_name, array('id' => $rule_id)); echo '<div class="notice notice-success"><p>规则已删除!</p></div>'; break; case 'bulk_update': // 这里可以实现批量更新产品价格的逻辑 echo '<div class="notice notice-success"><p>批量更新功能开发中...</p></div>'; break; } } } ?>
- <?php /** * 前端价格显示模板 * 在产品页面显示动态价格计算器 */ class SmartPricing_Frontend_Display { private static $instance = null; public static function get_instance() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } private function __construct() { add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts')); add_action('woocommerce_before_add_to_cart_button', array($this, 'display_pricing_calculator')); add_filter('woocommerce_get_price_html', array($this, 'display_dynamic_price_range'), 10, 2); } /** * 加载前端脚本和样式 */ public function enqueue_frontend_scripts() { if (!is_product()) { return; } wp_enqueue_style( 'smart-pricing-frontend', SMART_PRICING_PLUGIN_URL . 'assets/css/frontend.css', array(), SMART_PRICING_VERSION ); wp_enqueue_script( 'smart-pricing-frontend', SMART_PRICING_PLUGIN_URL . 'assets/js/frontend.js', array('jquery'), SMART_PRICING_VERSION, true ); global $product; wp_localize_script('smart-pricing-frontend', 'smartPricing', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('smart_pricing_nonce'), 'product_id' => $product->get_id(), 'base_price' => $product->get_price(), )); } /** * 显示价格计算器 */ public function display_pricing_calculator() { global $product; if (!$product || !$product->is_purchasable()) { return; } // 只对简单产品和变体产品显示 if (!$product->is_type('simple') && !$product->is_type('variable')) { return; } ?> <div class="smart-pricing-calculator" data-product-id="<?php echo esc_attr($product->get_id()); ?>" data-base-price="<?php echo esc_attr($product->get_price()); ?>"> <h3>批量报价计算器</h3> <p class="description">输入数量查看优惠价格</p> <!-- 内容由JavaScript动态生成 --> </div> <?php } /** * 显示动态价格范围 */ public function display_dynamic_price_range($price_html, $product) { if (is_admin() || !$product->is_type('simple')) { return $price_html; } // 获取价格范围 $price_range = $this->get_price_range($product); if ($price_range['min'] != $price_range['max']) { $price_html = sprintf( '<span class="price-range">%s - %s</span>', wc_price($price_range['min']), wc_price($price_range['max']) ); $price_html .= '<small class="price-range-note">(价格随数量变化)</small>'; }
在当今电子商务环境中,动态定价策略已成为提升竞争力的关键手段。对于使用WordPress的商家来说,实现智能报价与动态定价功能可以显著提高销售转化率和利润率。本教程将指导您开发一个轻量级WordPress插件,实现小批量定制产品的智能报价与动态定价功能。
我们的插件将实现以下核心功能:
- 根据产品数量自动计算折扣
- 考虑用户类型(新客户、VIP客户等)提供差异化定价
- 基于时间因素的动态定价(促销时段、季节性调整)
- 实时报价显示与更新
- 与WooCommerce的无缝集成
首先,我们创建插件的基本文件结构:
smart-pricing-plugin/
├── smart-pricing.php # 主插件文件
├── includes/
│ ├── class-pricing-engine.php
│ ├── class-ajax-handler.php
│ └── class-admin-settings.php
├── assets/
│ ├── css/
│ │ └── frontend.css
│ └── js/
│ └── frontend.js
└── templates/
└── pricing-display.php
<?php
/**
* Plugin Name: 智能报价与动态定价插件
* Plugin URI: https://yourwebsite.com/
* Description: 为WordPress网站提供小批量定制产品的智能报价与动态定价功能
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: smart-pricing
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('SMART_PRICING_VERSION', '1.0.0');
define('SMART_PRICING_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SMART_PRICING_PLUGIN_URL', plugin_dir_url(__FILE__));
// 自动加载类文件
spl_autoload_register(function ($class_name) {
if (strpos($class_name, 'SmartPricing_') === 0) {
$file = SMART_PRICING_PLUGIN_DIR . 'includes/class-' . strtolower(str_replace('_', '-', $class_name)) . '.php';
if (file_exists($file)) {
require_once $file;
}
}
});
// 初始化插件
function smart_pricing_init() {
// 检查WooCommerce是否激活
if (!class_exists('WooCommerce')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>智能报价插件需要WooCommerce支持,请先安装并激活WooCommerce插件。</p></div>';
});
return;
}
// 初始化核心类
SmartPricing_Pricing_Engine::get_instance();
SmartPricing_Ajax_Handler::get_instance();
if (is_admin()) {
SmartPricing_Admin_Settings::get_instance();
}
}
add_action('plugins_loaded', 'smart_pricing_init');
// 激活插件时的操作
register_activation_hook(__FILE__, 'smart_pricing_activate');
function smart_pricing_activate() {
// 创建必要的数据库表
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'smart_pricing_rules';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
rule_name varchar(100) NOT NULL,
min_quantity int NOT NULL DEFAULT 0,
max_quantity int NOT NULL DEFAULT 9999,
discount_type enum('percentage','fixed') DEFAULT 'percentage',
discount_value decimal(10,2) NOT NULL,
user_role varchar(50) DEFAULT '',
start_date datetime DEFAULT NULL,
end_date datetime DEFAULT NULL,
is_active tinyint(1) DEFAULT 1,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 添加默认定价规则
$default_rules = array(
array(
'rule_name' => '小批量折扣',
'min_quantity' => 10,
'max_quantity' => 50,
'discount_type' => 'percentage',
'discount_value' => 5.00,
'user_role' => '',
),
array(
'rule_name' => '中批量折扣',
'min_quantity' => 51,
'max_quantity' => 200,
'discount_type' => 'percentage',
'discount_value' => 10.00,
'user_role' => '',
),
array(
'rule_name' => 'VIP客户折扣',
'min_quantity' => 1,
'max_quantity' => 9999,
'discount_type' => 'percentage',
'discount_value' => 15.00,
'user_role' => 'vip_customer',
),
);
foreach ($default_rules as $rule) {
$wpdb->insert($table_name, $rule);
}
}
?>
<?php
/**
* Plugin Name: 智能报价与动态定价插件
* Plugin URI: https://yourwebsite.com/
* Description: 为WordPress网站提供小批量定制产品的智能报价与动态定价功能
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: smart-pricing
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('SMART_PRICING_VERSION', '1.0.0');
define('SMART_PRICING_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SMART_PRICING_PLUGIN_URL', plugin_dir_url(__FILE__));
// 自动加载类文件
spl_autoload_register(function ($class_name) {
if (strpos($class_name, 'SmartPricing_') === 0) {
$file = SMART_PRICING_PLUGIN_DIR . 'includes/class-' . strtolower(str_replace('_', '-', $class_name)) . '.php';
if (file_exists($file)) {
require_once $file;
}
}
});
// 初始化插件
function smart_pricing_init() {
// 检查WooCommerce是否激活
if (!class_exists('WooCommerce')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>智能报价插件需要WooCommerce支持,请先安装并激活WooCommerce插件。</p></div>';
});
return;
}
// 初始化核心类
SmartPricing_Pricing_Engine::get_instance();
SmartPricing_Ajax_Handler::get_instance();
if (is_admin()) {
SmartPricing_Admin_Settings::get_instance();
}
}
add_action('plugins_loaded', 'smart_pricing_init');
// 激活插件时的操作
register_activation_hook(__FILE__, 'smart_pricing_activate');
function smart_pricing_activate() {
// 创建必要的数据库表
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'smart_pricing_rules';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
rule_name varchar(100) NOT NULL,
min_quantity int NOT NULL DEFAULT 0,
max_quantity int NOT NULL DEFAULT 9999,
discount_type enum('percentage','fixed') DEFAULT 'percentage',
discount_value decimal(10,2) NOT NULL,
user_role varchar(50) DEFAULT '',
start_date datetime DEFAULT NULL,
end_date datetime DEFAULT NULL,
is_active tinyint(1) DEFAULT 1,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 添加默认定价规则
$default_rules = array(
array(
'rule_name' => '小批量折扣',
'min_quantity' => 10,
'max_quantity' => 50,
'discount_type' => 'percentage',
'discount_value' => 5.00,
'user_role' => '',
),
array(
'rule_name' => '中批量折扣',
'min_quantity' => 51,
'max_quantity' => 200,
'discount_type' => 'percentage',
'discount_value' => 10.00,
'user_role' => '',
),
array(
'rule_name' => 'VIP客户折扣',
'min_quantity' => 1,
'max_quantity' => 9999,
'discount_type' => 'percentage',
'discount_value' => 15.00,
'user_role' => 'vip_customer',
),
);
foreach ($default_rules as $rule) {
$wpdb->insert($table_name, $rule);
}
}
?>
<?php
/**
* 智能定价引擎类
* 负责计算动态价格和折扣
*/
class SmartPricing_Pricing_Engine {
private static $instance = null;
private $pricing_rules = array();
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->load_pricing_rules();
add_filter('woocommerce_product_get_price', array($this, 'calculate_dynamic_price'), 10, 2);
add_filter('woocommerce_product_variation_get_price', array($this, 'calculate_dynamic_price'), 10, 2);
add_action('woocommerce_before_calculate_totals', array($this, 'apply_cart_discounts'));
}
/**
* 从数据库加载定价规则
*/
private function load_pricing_rules() {
global $wpdb;
$table_name = $wpdb->prefix . 'smart_pricing_rules';
$this->pricing_rules = $wpdb->get_results(
"SELECT * FROM $table_name WHERE is_active = 1",
ARRAY_A
);
}
/**
* 计算动态价格
* @param float $price 原始价格
* @param WC_Product $product 产品对象
* @return float 计算后的价格
*/
public function calculate_dynamic_price($price, $product) {
// 只在特定页面应用动态定价
if (is_admin() && !defined('DOING_AJAX')) {
return $price;
}
// 获取当前用户信息
$user_id = get_current_user_id();
$user_roles = $user_id ? wp_get_current_user()->roles : array('guest');
// 获取产品数量(从购物车或通过AJAX传递)
$quantity = $this->get_product_quantity($product->get_id());
// 应用定价规则
$adjusted_price = $this->apply_pricing_rules($price, $quantity, $user_roles);
return max($adjusted_price, 0); // 确保价格不为负
}
/**
* 获取产品数量
* @param int $product_id 产品ID
* @return int 产品数量
*/
private function get_product_quantity($product_id) {
$quantity = 1; // 默认数量
// 从购物车获取数量
if (WC()->cart && !WC()->cart->is_empty()) {
foreach (WC()->cart->get_cart() as $cart_item) {
if ($cart_item['product_id'] == $product_id) {
$quantity = $cart_item['quantity'];
break;
}
}
}
// 允许通过AJAX覆盖数量
if (defined('DOING_AJAX') && DOING_AJAX && isset($_POST['quantity'])) {
$quantity = intval($_POST['quantity']);
}
return $quantity;
}
/**
* 应用定价规则
* @param float $base_price 基础价格
* @param int $quantity 数量
* @param array $user_roles 用户角色
* @return float 调整后的价格
*/
private function apply_pricing_rules($base_price, $quantity, $user_roles) {
$best_price = $base_price;
$current_time = current_time('mysql');
foreach ($this->pricing_rules as $rule) {
// 检查数量范围
if ($quantity < $rule['min_quantity'] || $quantity > $rule['max_quantity']) {
continue;
}
// 检查用户角色
if (!empty($rule['user_role']) && !in_array($rule['user_role'], $user_roles)) {
continue;
}
// 检查时间有效性
if ($rule['start_date'] && $rule['start_date'] > $current_time) {
continue;
}
if ($rule['end_date'] && $rule['end_date'] < $current_time) {
continue;
}
// 计算折扣价格
$discounted_price = $this->calculate_discount($base_price, $rule);
// 选择最优价格(最低价格)
if ($discounted_price < $best_price) {
$best_price = $discounted_price;
}
}
return $best_price;
}
/**
* 计算折扣
* @param float $price 原始价格
* @param array $rule 定价规则
* @return float 折扣后价格
*/
private function calculate_discount($price, $rule) {
if ($rule['discount_type'] == 'percentage') {
$discount = $price * ($rule['discount_value'] / 100);
return $price - $discount;
} else {
return max($price - $rule['discount_value'], 0);
}
}
/**
* 应用购物车折扣
* @param WC_Cart $cart 购物车对象
*/
public function apply_cart_discounts($cart) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
// 这里可以添加购物车级别的折扣逻辑
// 例如:基于总金额的折扣或组合产品折扣
}
}
?>
<?php
/**
* 智能定价引擎类
* 负责计算动态价格和折扣
*/
class SmartPricing_Pricing_Engine {
private static $instance = null;
private $pricing_rules = array();
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->load_pricing_rules();
add_filter('woocommerce_product_get_price', array($this, 'calculate_dynamic_price'), 10, 2);
add_filter('woocommerce_product_variation_get_price', array($this, 'calculate_dynamic_price'), 10, 2);
add_action('woocommerce_before_calculate_totals', array($this, 'apply_cart_discounts'));
}
/**
* 从数据库加载定价规则
*/
private function load_pricing_rules() {
global $wpdb;
$table_name = $wpdb->prefix . 'smart_pricing_rules';
$this->pricing_rules = $wpdb->get_results(
"SELECT * FROM $table_name WHERE is_active = 1",
ARRAY_A
);
}
/**
* 计算动态价格
* @param float $price 原始价格
* @param WC_Product $product 产品对象
* @return float 计算后的价格
*/
public function calculate_dynamic_price($price, $product) {
// 只在特定页面应用动态定价
if (is_admin() && !defined('DOING_AJAX')) {
return $price;
}
// 获取当前用户信息
$user_id = get_current_user_id();
$user_roles = $user_id ? wp_get_current_user()->roles : array('guest');
// 获取产品数量(从购物车或通过AJAX传递)
$quantity = $this->get_product_quantity($product->get_id());
// 应用定价规则
$adjusted_price = $this->apply_pricing_rules($price, $quantity, $user_roles);
return max($adjusted_price, 0); // 确保价格不为负
}
/**
* 获取产品数量
* @param int $product_id 产品ID
* @return int 产品数量
*/
private function get_product_quantity($product_id) {
$quantity = 1; // 默认数量
// 从购物车获取数量
if (WC()->cart && !WC()->cart->is_empty()) {
foreach (WC()->cart->get_cart() as $cart_item) {
if ($cart_item['product_id'] == $product_id) {
$quantity = $cart_item['quantity'];
break;
}
}
}
// 允许通过AJAX覆盖数量
if (defined('DOING_AJAX') && DOING_AJAX && isset($_POST['quantity'])) {
$quantity = intval($_POST['quantity']);
}
return $quantity;
}
/**
* 应用定价规则
* @param float $base_price 基础价格
* @param int $quantity 数量
* @param array $user_roles 用户角色
* @return float 调整后的价格
*/
private function apply_pricing_rules($base_price, $quantity, $user_roles) {
$best_price = $base_price;
$current_time = current_time('mysql');
foreach ($this->pricing_rules as $rule) {
// 检查数量范围
if ($quantity < $rule['min_quantity'] || $quantity > $rule['max_quantity']) {
continue;
}
// 检查用户角色
if (!empty($rule['user_role']) && !in_array($rule['user_role'], $user_roles)) {
continue;
}
// 检查时间有效性
if ($rule['start_date'] && $rule['start_date'] > $current_time) {
continue;
}
if ($rule['end_date'] && $rule['end_date'] < $current_time) {
continue;
}
// 计算折扣价格
$discounted_price = $this->calculate_discount($base_price, $rule);
// 选择最优价格(最低价格)
if ($discounted_price < $best_price) {
$best_price = $discounted_price;
}
}
return $best_price;
}
/**
* 计算折扣
* @param float $price 原始价格
* @param array $rule 定价规则
* @return float 折扣后价格
*/
private function calculate_discount($price, $rule) {
if ($rule['discount_type'] == 'percentage') {
$discount = $price * ($rule['discount_value'] / 100);
return $price - $discount;
} else {
return max($price - $rule['discount_value'], 0);
}
}
/**
* 应用购物车折扣
* @param WC_Cart $cart 购物车对象
*/
public function apply_cart_discounts($cart) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
// 这里可以添加购物车级别的折扣逻辑
// 例如:基于总金额的折扣或组合产品折扣
}
}
?>
<?php
/**
* AJAX请求处理器
* 处理前端实时报价请求
*/
class SmartPricing_Ajax_Handler {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('wp_ajax_get_dynamic_price', array($this, 'get_dynamic_price_ajax'));
add_action('wp_ajax_nopriv_get_dynamic_price', array($this, 'get_dynamic_price_ajax'));
}
/**
* 处理动态价格AJAX请求
*/
public function get_dynamic_price_ajax() {
// 验证nonce
if (!check_ajax_referer('smart_pricing_nonce', 'security', false)) {
wp_die('安全验证失败');
}
// 获取请求参数
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity']);
// 验证参数
if ($product_id <= 0 || $quantity <= 0) {
wp_send_json_error('参数无效');
}
// 获取产品
$product = wc_get_product($product_id);
if (!$product) {
wp_send_json_error('产品不存在');
}
// 获取基础价格
$base_price = $product->get_price();
// 创建临时定价引擎实例
$pricing_engine = SmartPricing_Pricing_Engine::get_instance();
// 使用反射调用私有方法(实际应用中应优化此部分)
$reflection = new ReflectionClass($pricing_engine);
$method = $reflection->getMethod('apply_pricing_rules');
$method->setAccessible(true);
// 获取用户角色
$user_id = get_current_user_id();
$user_roles = $user_id ? wp_get_current_user()->roles : array('guest');
// 计算动态价格
$dynamic_price = $method->invoke($pricing_engine, $base_price, $quantity, $user_roles);
// 计算节省金额
$savings = $base_price * $quantity - $dynamic_price * $quantity;
// 准备响应数据
$response = array(
'success' => true,
'data' => array(
'base_price' => wc_price($base_price),
'dynamic_price' => wc_price($dynamic_price),
'total_base' => wc_price($base_price * $quantity),
'total_dynamic' => wc_price($dynamic_price * $quantity),
'savings' => wc_price($savings),
'savings_percentage' => $base_price > 0 ? round(($savings / ($base_price * $quantity)) * 100, 2) : 0,
'quantity' => $quantity,
),
);
wp_send_json($response);
}
}
?>
<?php
/**
* AJAX请求处理器
* 处理前端实时报价请求
*/
class SmartPricing_Ajax_Handler {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('wp_ajax_get_dynamic_price', array($this, 'get_dynamic_price_ajax'));
add_action('wp_ajax_nopriv_get_dynamic_price', array($this, 'get_dynamic_price_ajax'));
}
/**
* 处理动态价格AJAX请求
*/
public function get_dynamic_price_ajax() {
// 验证nonce
if (!check_ajax_referer('smart_pricing_nonce', 'security', false)) {
wp_die('安全验证失败');
}
// 获取请求参数
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity']);
// 验证参数
if ($product_id <= 0 || $quantity <= 0) {
wp_send_json_error('参数无效');
}
// 获取产品
$product = wc_get_product($product_id);
if (!$product) {
wp_send_json_error('产品不存在');
}
// 获取基础价格
$base_price = $product->get_price();
// 创建临时定价引擎实例
$pricing_engine = SmartPricing_Pricing_Engine::get_instance();
// 使用反射调用私有方法(实际应用中应优化此部分)
$reflection = new ReflectionClass($pricing_engine);
$method = $reflection->getMethod('apply_pricing_rules');
$method->setAccessible(true);
// 获取用户角色
$user_id = get_current_user_id();
$user_roles = $user_id ? wp_get_current_user()->roles : array('guest');
// 计算动态价格
$dynamic_price = $method->invoke($pricing_engine, $base_price, $quantity, $user_roles);
// 计算节省金额
$savings = $base_price * $quantity - $dynamic_price * $quantity;
// 准备响应数据
$response = array(
'success' => true,
'data' => array(
'base_price' => wc_price($base_price),
'dynamic_price' => wc_price($dynamic_price),
'total_base' => wc_price($base_price * $quantity),
'total_dynamic' => wc_price($dynamic_price * $quantity),
'savings' => wc_price($savings),
'savings_percentage' => $base_price > 0 ? round(($savings / ($base_price * $quantity)) * 100, 2) : 0,
'quantity' => $quantity,
),
);
wp_send_json($response);
}
}
?>
/**
* 前端动态报价交互
*/
jQuery(document).ready(function($) {
// 初始化报价计算器
function initPricingCalculator() {
$('.smart-pricing-calculator').each(function() {
var $calculator = $(this);
var productId = $calculator.data('product-id');
var basePrice = $calculator.data('base-price');
// 创建数量输入
var $quantityInput = $('<input>', {
type: 'number',
min: 1,
value: 1,
class: 'pricing-quantity'
});
// 创建计算按钮
var $calculateBtn = $('<button>', {
text: '计算报价',
class: 'button pricing-calculate-btn'
});
// 创建结果显示区域
var $results = $('<div>', {
class: 'pricing-results',
html: '<div class="price-breakdown"></div>'
});
// 组装计算器
$calculator.append(
$('<div class="quantity-selector">').append(
$('<label>').text('数量: '),
$quantityInput
),
$calculateBtn,
$results
);
// 绑定计算事件
$calculateBtn.on('click', function() {
calculateDynamicPrice(productId, $quantityInput.val(), $results);
});
// 实时计算(输入时自动计算)
$quantityInput.on('input', function() {
calculateDynamicPrice(productId, $(this).val(), $results);
});
// 初始计算
calculateDynamicPrice(productId, 1, $results);
});
}
// 计算动态价格
function calculateDynamicPrice(productId, quantity, $resultsContainer) {
if (!productId || quantity < 1) {
return;
}
// 显示加载状态
$resultsContainer.find('.price-breakdown').html('<div class="loading">计算中...</div>');
// 发送AJAX请求
$.ajax({
url: smartPricing.ajax_url,
type: 'POST',
data: {
action: 'get_dynamic_price',
product_id: productId,
quantity: quantity,
security: smartPricing.nonce
},
success: function(response) {
if (response.success) {
var data = response.data;
var html = `
<div class="price-summary">
<h4>报价详情</h4>
<table class="price-table">
<tr>
<td>单价:</td>
<td>${data.base_price} → <strong>${data.dynamic_price}</strong></td>
</tr>
<tr>
<td>${quantity}件总价:</td>
<td>${data.total_base} → <strong>${data.total_dynamic}</strong></td>
</tr>
<tr class="savings-row">
<td>节省金额:</td>
<td class="savings-amount">${data.savings} (${data.savings_percentage}%)</td>
</tr>
</table>
</div>
`;
$resultsContainer.find('.price-breakdown').html(html);
} else {
$resultsContainer.find('.price-breakdown').html('<div class="error">计算失败,请重试</div>');
}
},
error: function() {
$resultsContainer.find('.price-breakdown').html('<div class="error">网络错误,请刷新页面</div>');
}
});
}
// 初始化
initPricingCalculator();
// 添加到购物车时更新价格显示
$(document).on('found_variation', function(event, variation) {
// 当产品变体选择时更新价格计算器
setTimeout(initPricingCalculator, 100);
});
});
/**
* 前端动态报价交互
*/
jQuery(document).ready(function($) {
// 初始化报价计算器
function initPricingCalculator() {
$('.smart-pricing-calculator').each(function() {
var $calculator = $(this);
var productId = $calculator.data('product-id');
var basePrice = $calculator.data('base-price');
// 创建数量输入
var $quantityInput = $('<input>', {
type: 'number',
min: 1,
value: 1,
class: 'pricing-quantity'
});
// 创建计算按钮
var $calculateBtn = $('<button>', {
text: '计算报价',
class: 'button pricing-calculate-btn'
});
// 创建结果显示区域
var $results = $('<div>', {
class: 'pricing-results',
html: '<div class="price-breakdown"></div>'
});
// 组装计算器
$calculator.append(
$('<div class="quantity-selector">').append(
$('<label>').text('数量: '),
$quantityInput
),
$calculateBtn,
$results
);
// 绑定计算事件
$calculateBtn.on('click', function() {
calculateDynamicPrice(productId, $quantityInput.val(), $results);
});
// 实时计算(输入时自动计算)
$quantityInput.on('input', function() {
calculateDynamicPrice(productId, $(this).val(), $results);
});
// 初始计算
calculateDynamicPrice(productId, 1, $results);
});
}
// 计算动态价格
function calculateDynamicPrice(productId, quantity, $resultsContainer) {
if (!productId || quantity < 1) {
return;
}
// 显示加载状态
$resultsContainer.find('.price-breakdown').html('<div class="loading">计算中...</div>');
// 发送AJAX请求
$.ajax({
url: smartPricing.ajax_url,
type: 'POST',
data: {
action: 'get_dynamic_price',
product_id: productId,
quantity: quantity,
security: smartPricing.nonce
},
success: function(response) {
if (response.success) {
var data = response.data;
var html = `
<div class="price-summary">
<h4>报价详情</h4>
<table class="price-table">
<tr>
<td>单价:</td>
<td>${data.base_price} → <strong>${data.dynamic_price}</strong></td>
</tr>
<tr>
<td>${quantity}件总价:</td>
<td>${data.total_base} → <strong>${data.total_dynamic}</strong></td>
</tr>
<tr class="savings-row">
<td>节省金额:</td>
<td class="savings-amount">${data.savings} (${data.savings_percentage}%)</td>
</tr>
</table>
</div>
`;
$resultsContainer.find('.price-breakdown').html(html);
} else {
$resultsContainer.find('.price-breakdown').html('<div class="error">计算失败,请重试</div>');
}
},
error: function() {
$resultsContainer.find('.price-breakdown').html('<div class="error">网络错误,请刷新页面</div>');
}
});
}
// 初始化
initPricingCalculator();
// 添加到购物车时更新价格显示
$(document).on('found_variation', function(event, variation) {
// 当产品变体选择时更新价格计算器
setTimeout(initPricingCalculator, 100);
});
});
<?php
/**
* 管理设置类
* 提供定价规则管理界面
*/
class SmartPricing_Admin_Settings {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
add_action('admin_init', array($this, 'register_settings'));
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_submenu_page(
'woocommerce',
'智能定价设置',
'智能定价',
'manage_options',
'smart-pricing-settings',
array($this, 'render_settings_page')
);
}
/**
* 加载管理端脚本和样式
*/
public function enqueue_admin_scripts($hook) {
if ('woocommerce_page_smart-pricing-settings' !== $hook) {
return;
}
wp_enqueue_style(
'smart-pricing-admin',
SMART_PRICING_PLUGIN_URL . 'assets/css/admin.css',
array(),
SMART_PRICING_VERSION
);
wp_enqueue_script(
'smart-pricing-admin',
SMART_PRICING_PLUGIN_URL . 'assets/js/admin.js',
array('jquery', 'jquery-ui-datepicker'),
SMART_PRICING_VERSION,
true
);
wp_localize_script('smart-pricing-admin', 'smartPricingAdmin', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('smart_pricing_admin_nonce'),
'confirm_delete' => __('确定要删除这条规则吗?', 'smart-pricing'),
));
}
/**
* 注册设置选项
*/
public function register_settings() {
register_setting('smart_pricing_settings', 'smart_pricing_options');
add_settings_section(
'smart_pricing_main',
'定价规则管理',
array($this, 'render_section_callback'),
'smart-pricing-settings'
);
}
/**
* 渲染设置页面
*/
public function render_settings_page() {
if (!current_user_can('manage_options')) {
wp_die('权限不足');
}
// 处理表单提交
$this->handle_form_submissions();
// 获取所有定价规则
global $wpdb;
$table_name = $wpdb->prefix . 'smart_pricing_rules';
$rules = $wpdb->get_results("SELECT * FROM $table_name ORDER BY min_quantity ASC", ARRAY_A);
// 获取用户角色
$user_roles = get_editable_roles();
?>
<div class="wrap smart-pricing-settings">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<div class="notice notice-info">
<p>在此管理智能定价规则。规则按优先级从上到下应用,匹配的第一个规则将被使用。</p>
</div>
<!-- 添加新规则表单 -->
<div class="card">
<h2>添加新定价规则</h2>
<form method="post" action="">
<?php wp_nonce_field('smart_pricing_add_rule', 'smart_pricing_nonce'); ?>
<input type="hidden" name="action" value="add_rule">
<table class="form-table">
<tr>
<th scope="row"><label for="rule_name">规则名称</label></th>
<td>
<input type="text" id="rule_name" name="rule_name"
class="regular-text" required>
</td>
</tr>
<tr>
<th scope="row"><label for="min_quantity">最小数量</label></th>
<td>
<input type="number" id="min_quantity" name="min_quantity"
min="0" value="0" class="small-text" required>
</td>
</tr>
<tr>
<th scope="row"><label for="max_quantity">最大数量</label></th>
<td>
<input type="number" id="max_quantity" name="max_quantity"
min="1" value="9999" class="small-text" required>
<p class="description">设置为9999表示无上限</p>
</td>
</tr>
<tr>
<th scope="row"><label>折扣类型</label></th>
<td>
<label>
<input type="radio" name="discount_type" value="percentage" checked>
百分比折扣
</label>
<label style="margin-left: 20px;">
<input type="radio" name="discount_type" value="fixed">
固定金额折扣
</label>
</td>
</tr>
<tr>
<th scope="row"><label for="discount_value">折扣值</label></th>
<td>
<input type="number" id="discount_value" name="discount_value"
step="0.01" min="0" class="small-text" required>
<span class="discount-unit">%</span>
</td>
</tr>
<tr>
<th scope="row"><label for="user_role">适用用户角色</label></th>
<td>
<select id="user_role" name="user_role">
<option value="">所有用户</option>
<?php foreach ($user_roles as $role => $details): ?>
<option value="<?php echo esc_attr($role); ?>">
<?php echo esc_html($details['name']); ?>
</option>
<?php endforeach; ?>
</select>
<p class="description">留空表示适用于所有用户</p>
</td>
</tr>
<tr>
<th scope="row"><label for="start_date">生效时间</label></th>
<td>
<input type="text" id="start_date" name="start_date"
class="datepicker" placeholder="YYYY-MM-DD">
<p class="description">留空表示立即生效</p>
</td>
</tr>
<tr>
<th scope="row"><label for="end_date">结束时间</label></th>
<td>
<input type="text" id="end_date" name="end_date"
class="datepicker" placeholder="YYYY-MM-DD">
<p class="description">留空表示永久有效</p>
</td>
</tr>
</table>
<?php submit_button('添加规则', 'primary', 'submit_rule'); ?>
</form>
</div>
<!-- 现有规则列表 -->
<div class="card">
<h2>现有定价规则</h2>
<?php if (empty($rules)): ?>
<p>暂无定价规则。</p>
<?php else: ?>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>规则名称</th>
<th>数量范围</th>
<th>折扣</th>
<th>适用角色</th>
<th>生效时间</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($rules as $rule): ?>
<tr>
<td><?php echo esc_html($rule['rule_name']); ?></td>
<td>
<?php
echo esc_html($rule['min_quantity']);
echo ' - ';
echo $rule['max_quantity'] == 9999 ? '∞' : esc_html($rule['max_quantity']);
?>
</td>
<td>
<?php
if ($rule['discount_type'] == 'percentage') {
echo esc_html($rule['discount_value']) . '%';
} else {
echo '¥' . esc_html($rule['discount_value']);
}
?>
</td>
<td>
<?php
echo empty($rule['user_role'])
? '所有用户'
: esc_html($rule['user_role']);
?>
</td>
<td>
<?php
$dates = array();
if ($rule['start_date']) {
$dates[] = date('Y-m-d', strtotime($rule['start_date']));
}
if ($rule['end_date']) {
$dates[] = date('Y-m-d', strtotime($rule['end_date']));
}
echo $dates ? implode(' 至 ', $dates) : '永久';
?>
</td>
<td>
<?php if ($rule['is_active']): ?>
<span class="status-active">启用</span>
<?php else: ?>
<span class="status-inactive">禁用</span>
<?php endif; ?>
</td>
<td>
<form method="post" action="" style="display: inline;">
<?php wp_nonce_field('smart_pricing_toggle_rule', 'smart_pricing_nonce'); ?>
<input type="hidden" name="action" value="toggle_rule">
<input type="hidden" name="rule_id" value="<?php echo esc_attr($rule['id']); ?>">
<button type="submit" class="button button-small">
<?php echo $rule['is_active'] ? '禁用' : '启用'; ?>
</button>
</form>
<form method="post" action="" style="display: inline;">
<?php wp_nonce_field('smart_pricing_delete_rule', 'smart_pricing_nonce'); ?>
<input type="hidden" name="action" value="delete_rule">
<input type="hidden" name="rule_id" value="<?php echo esc_attr($rule['id']); ?>">
<button type="submit" class="button button-small button-delete"
onclick="return confirm('确定要删除这条规则吗?');">
删除
</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- 批量定价工具 -->
<div class="card">
<h2>批量定价工具</h2>
<form method="post" action="">
<?php wp_nonce_field('smart_pricing_bulk_update', 'smart_pricing_nonce'); ?>
<input type="hidden" name="action" value="bulk_update">
<table class="form-table">
<tr>
<th scope="row"><label>应用范围</label></th>
<td>
<select name="product_scope">
<option value="all">所有产品</option>
<option value="category">特定分类</option>
<option value="selected">选定产品</option>
</select>
</td>
</tr>
<tr>
<th scope="row"><label>定价规则</label></th>
<td>
<select name="pricing_rule">
<option value="">-- 选择规则 --</option>
<?php foreach ($rules as $rule): ?>
<?php if ($rule['is_active']): ?>
<option value="<?php echo esc_attr($rule['id']); ?>">
<?php echo esc_html($rule['rule_name']); ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</td>
</tr>
</table>
<?php submit_button('应用批量定价', 'secondary', 'submit_bulk'); ?>
</form>
</div>
</div>
<script>
jQuery(document).ready(function($) {
// 日期选择器
$('.datepicker').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true
});
// 折扣类型切换
$('input[name="discount_type"]').change(function() {
var unit = $(this).val() === 'percentage' ? '%' : '¥';
$('.discount-unit').text(unit);
});
});
</script>
<?php
}
/**
* 处理表单提交
*/
private function handle_form_submissions() {
if (!isset($_POST['action'])) {
return;
}
// 验证nonce
if (!isset($_POST['smart_pricing_nonce']) ||
!wp_verify_nonce($_POST['smart_pricing_nonce'], 'smart_pricing_' . $_POST['action'])) {
wp_die('安全验证失败');
}
global $wpdb;
$table_name = $wpdb->prefix . 'smart_pricing_rules';
switch ($_POST['action']) {
case 'add_rule':
$data = array(
'rule_name' => sanitize_text_field($_POST['rule_name']),
'min_quantity' => intval($_POST['min_quantity']),
'max_quantity' => intval($_POST['max_quantity']),
'discount_type' => sanitize_text_field($_POST['discount_type']),
'discount_value' => floatval($_POST['discount_value']),
'user_role' => sanitize_text_field($_POST['user_role']),
'start_date' => !empty($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) . ' 00:00:00' : null,
'end_date' => !empty($_POST['end_date']) ? sanitize_text_field($_POST['end_date']) . ' 23:59:59' : null,
'is_active' => 1,
);
$wpdb->insert($table_name, $data);
echo '<div class="notice notice-success"><p>规则添加成功!</p></div>';
break;
case 'toggle_rule':
$rule_id = intval($_POST['rule_id']);
$current_status = $wpdb->get_var(
$wpdb->prepare("SELECT is_active FROM $table_name WHERE id = %d", $rule_id)
);
$wpdb->update(
$table_name,
array('is_active' => $current_status ? 0 : 1),
array('id' => $rule_id)
);
echo '<div class="notice notice-success"><p>规则状态已更新!</p></div>';
break;
case 'delete_rule':
$rule_id = intval($_POST['rule_id']);
$wpdb->delete($table_name, array('id' => $rule_id));
echo '<div class="notice notice-success"><p>规则已删除!</p></div>';
break;
case 'bulk_update':
// 这里可以实现批量更新产品价格的逻辑
echo '<div class="notice notice-success"><p>批量更新功能开发中...</p></div>';
break;
}
}
}
?>
<?php
/**
* 管理设置类
* 提供定价规则管理界面
*/
class SmartPricing_Admin_Settings {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
add_action('admin_init', array($this, 'register_settings'));
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_submenu_page(
'woocommerce',
'智能定价设置',
'智能定价',
'manage_options',
'smart-pricing-settings',
array($this, 'render_settings_page')
);
}
/**
* 加载管理端脚本和样式
*/
public function enqueue_admin_scripts($hook) {
if ('woocommerce_page_smart-pricing-settings' !== $hook) {
return;
}
wp_enqueue_style(
'smart-pricing-admin',
SMART_PRICING_PLUGIN_URL . 'assets/css/admin.css',
array(),
SMART_PRICING_VERSION
);
wp_enqueue_script(
'smart-pricing-admin',
SMART_PRICING_PLUGIN_URL . 'assets/js/admin.js',
array('jquery', 'jquery-ui-datepicker'),
SMART_PRICING_VERSION,
true
);
wp_localize_script('smart-pricing-admin', 'smartPricingAdmin', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('smart_pricing_admin_nonce'),
'confirm_delete' => __('确定要删除这条规则吗?', 'smart-pricing'),
));
}
/**
* 注册设置选项
*/
public function register_settings() {
register_setting('smart_pricing_settings', 'smart_pricing_options');
add_settings_section(
'smart_pricing_main',
'定价规则管理',
array($this, 'render_section_callback'),
'smart-pricing-settings'
);
}
/**
* 渲染设置页面
*/
public function render_settings_page() {
if (!current_user_can('manage_options')) {
wp_die('权限不足');
}
// 处理表单提交
$this->handle_form_submissions();
// 获取所有定价规则
global $wpdb;
$table_name = $wpdb->prefix . 'smart_pricing_rules';
$rules = $wpdb->get_results("SELECT * FROM $table_name ORDER BY min_quantity ASC", ARRAY_A);
// 获取用户角色
$user_roles = get_editable_roles();
?>
<div class="wrap smart-pricing-settings">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<div class="notice notice-info">
<p>在此管理智能定价规则。规则按优先级从上到下应用,匹配的第一个规则将被使用。</p>
</div>
<!-- 添加新规则表单 -->
<div class="card">
<h2>添加新定价规则</h2>
<form method="post" action="">
<?php wp_nonce_field('smart_pricing_add_rule', 'smart_pricing_nonce'); ?>
<input type="hidden" name="action" value="add_rule">
<table class="form-table">
<tr>
<th scope="row"><label for="rule_name">规则名称</label></th>
<td>
<input type="text" id="rule_name" name="rule_name"
class="regular-text" required>
</td>
</tr>
<tr>
<th scope="row"><label for="min_quantity">最小数量</label></th>
<td>
<input type="number" id="min_quantity" name="min_quantity"
min="0" value="0" class="small-text" required>
</td>
</tr>
<tr>
<th scope="row"><label for="max_quantity">最大数量</label></th>
<td>
<input type="number" id="max_quantity" name="max_quantity"
min="1" value="9999" class="small-text" required>
<p class="description">设置为9999表示无上限</p>
</td>
</tr>
<tr>
<th scope="row"><label>折扣类型</label></th>
<td>
<label>
<input type="radio" name="discount_type" value="percentage" checked>
百分比折扣
</label>
<label style="margin-left: 20px;">
<input type="radio" name="discount_type" value="fixed">
固定金额折扣
</label>
</td>
</tr>
<tr>
<th scope="row"><label for="discount_value">折扣值</label></th>
<td>
<input type="number" id="discount_value" name="discount_value"
step="0.01" min="0" class="small-text" required>
<span class="discount-unit">%</span>
</td>
</tr>
<tr>
<th scope="row"><label for="user_role">适用用户角色</label></th>
<td>
<select id="user_role" name="user_role">
<option value="">所有用户</option>
<?php foreach ($user_roles as $role => $details): ?>
<option value="<?php echo esc_attr($role); ?>">
<?php echo esc_html($details['name']); ?>
</option>
<?php endforeach; ?>
</select>
<p class="description">留空表示适用于所有用户</p>
</td>
</tr>
<tr>
<th scope="row"><label for="start_date">生效时间</label></th>
<td>
<input type="text" id="start_date" name="start_date"
class="datepicker" placeholder="YYYY-MM-DD">
<p class="description">留空表示立即生效</p>
</td>
</tr>
<tr>
<th scope="row"><label for="end_date">结束时间</label></th>
<td>
<input type="text" id="end_date" name="end_date"
class="datepicker" placeholder="YYYY-MM-DD">
<p class="description">留空表示永久有效</p>
</td>
</tr>
</table>
<?php submit_button('添加规则', 'primary', 'submit_rule'); ?>
</form>
</div>
<!-- 现有规则列表 -->
<div class="card">
<h2>现有定价规则</h2>
<?php if (empty($rules)): ?>
<p>暂无定价规则。</p>
<?php else: ?>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>规则名称</th>
<th>数量范围</th>
<th>折扣</th>
<th>适用角色</th>
<th>生效时间</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($rules as $rule): ?>
<tr>
<td><?php echo esc_html($rule['rule_name']); ?></td>
<td>
<?php
echo esc_html($rule['min_quantity']);
echo ' - ';
echo $rule['max_quantity'] == 9999 ? '∞' : esc_html($rule['max_quantity']);
?>
</td>
<td>
<?php
if ($rule['discount_type'] == 'percentage') {
echo esc_html($rule['discount_value']) . '%';
} else {
echo '¥' . esc_html($rule['discount_value']);
}
?>
</td>
<td>
<?php
echo empty($rule['user_role'])
? '所有用户'
: esc_html($rule['user_role']);
?>
</td>
<td>
<?php
$dates = array();
if ($rule['start_date']) {
$dates[] = date('Y-m-d', strtotime($rule['start_date']));
}
if ($rule['end_date']) {
$dates[] = date('Y-m-d', strtotime($rule['end_date']));
}
echo $dates ? implode(' 至 ', $dates) : '永久';
?>
</td>
<td>
<?php if ($rule['is_active']): ?>
<span class="status-active">启用</span>
<?php else: ?>
<span class="status-inactive">禁用</span>
<?php endif; ?>
</td>
<td>
<form method="post" action="" style="display: inline;">
<?php wp_nonce_field('smart_pricing_toggle_rule', 'smart_pricing_nonce'); ?>
<input type="hidden" name="action" value="toggle_rule">
<input type="hidden" name="rule_id" value="<?php echo esc_attr($rule['id']); ?>">
<button type="submit" class="button button-small">
<?php echo $rule['is_active'] ? '禁用' : '启用'; ?>
</button>
</form>
<form method="post" action="" style="display: inline;">
<?php wp_nonce_field('smart_pricing_delete_rule', 'smart_pricing_nonce'); ?>
<input type="hidden" name="action" value="delete_rule">
<input type="hidden" name="rule_id" value="<?php echo esc_attr($rule['id']); ?>">
<button type="submit" class="button button-small button-delete"
onclick="return confirm('确定要删除这条规则吗?');">
删除
</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- 批量定价工具 -->
<div class="card">
<h2>批量定价工具</h2>
<form method="post" action="">
<?php wp_nonce_field('smart_pricing_bulk_update', 'smart_pricing_nonce'); ?>
<input type="hidden" name="action" value="bulk_update">
<table class="form-table">
<tr>
<th scope="row"><label>应用范围</label></th>
<td>
<select name="product_scope">
<option value="all">所有产品</option>
<option value="category">特定分类</option>
<option value="selected">选定产品</option>
</select>
</td>
</tr>
<tr>
<th scope="row"><label>定价规则</label></th>
<td>
<select name="pricing_rule">
<option value="">-- 选择规则 --</option>
<?php foreach ($rules as $rule): ?>
<?php if ($rule['is_active']): ?>
<option value="<?php echo esc_attr($rule['id']); ?>">
<?php echo esc_html($rule['rule_name']); ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</td>
</tr>
</table>
<?php submit_button('应用批量定价', 'secondary', 'submit_bulk'); ?>
</form>
</div>
</div>
<script>
jQuery(document).ready(function($) {
// 日期选择器
$('.datepicker').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true
});
// 折扣类型切换
$('input[name="discount_type"]').change(function() {
var unit = $(this).val() === 'percentage' ? '%' : '¥';
$('.discount-unit').text(unit);
});
});
</script>
<?php
}
/**
* 处理表单提交
*/
private function handle_form_submissions() {
if (!isset($_POST['action'])) {
return;
}
// 验证nonce
if (!isset($_POST['smart_pricing_nonce']) ||
!wp_verify_nonce($_POST['smart_pricing_nonce'], 'smart_pricing_' . $_POST['action'])) {
wp_die('安全验证失败');
}
global $wpdb;
$table_name = $wpdb->prefix . 'smart_pricing_rules';
switch ($_POST['action']) {
case 'add_rule':
$data = array(
'rule_name' => sanitize_text_field($_POST['rule_name']),
'min_quantity' => intval($_POST['min_quantity']),
'max_quantity' => intval($_POST['max_quantity']),
'discount_type' => sanitize_text_field($_POST['discount_type']),
'discount_value' => floatval($_POST['discount_value']),
'user_role' => sanitize_text_field($_POST['user_role']),
'start_date' => !empty($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) . ' 00:00:00' : null,
'end_date' => !empty($_POST['end_date']) ? sanitize_text_field($_POST['end_date']) . ' 23:59:59' : null,
'is_active' => 1,
);
$wpdb->insert($table_name, $data);
echo '<div class="notice notice-success"><p>规则添加成功!</p></div>';
break;
case 'toggle_rule':
$rule_id = intval($_POST['rule_id']);
$current_status = $wpdb->get_var(
$wpdb->prepare("SELECT is_active FROM $table_name WHERE id = %d", $rule_id)
);
$wpdb->update(
$table_name,
array('is_active' => $current_status ? 0 : 1),
array('id' => $rule_id)
);
echo '<div class="notice notice-success"><p>规则状态已更新!</p></div>';
break;
case 'delete_rule':
$rule_id = intval($_POST['rule_id']);
$wpdb->delete($table_name, array('id' => $rule_id));
echo '<div class="notice notice-success"><p>规则已删除!</p></div>';
break;
case 'bulk_update':
// 这里可以实现批量更新产品价格的逻辑
echo '<div class="notice notice-success"><p>批量更新功能开发中...</p></div>';
break;
}
}
}
?>
<?php
/**
* 前端价格显示模板
* 在产品页面显示动态价格计算器
*/
class SmartPricing_Frontend_Display {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
add_action('woocommerce_before_add_to_cart_button', array($this, 'display_pricing_calculator'));
add_filter('woocommerce_get_price_html', array($this, 'display_dynamic_price_range'), 10, 2);
}
/**
* 加载前端脚本和样式
*/
public function enqueue_frontend_scripts() {
if (!is_product()) {
return;
}
wp_enqueue_style(
'smart-pricing-frontend',
SMART_PRICING_PLUGIN_URL . 'assets/css/frontend.css',
array(),
SMART_PRICING_VERSION
);
wp_enqueue_script(
'smart-pricing-frontend',
SMART_PRICING_PLUGIN_URL . 'assets/js/frontend.js',
array('jquery'),
SMART_PRICING_VERSION,
true
);
global $product;
wp_localize_script('smart-pricing-frontend', 'smartPricing', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('smart_pricing_nonce'),
'product_id' => $product->get_id(),
'base_price' => $product->get_price(),
));
}
/**
* 显示价格计算器
*/
public function display_pricing_calculator() {
global $product;
if (!$product || !$product->is_purchasable()) {
return;
}
// 只对简单产品和变体产品显示
if (!$product->is_type('simple') && !$product->is_type('variable')) {
return;
}
?>
<div class="smart-pricing-calculator"
data-product-id="<?php echo esc_attr($product->get_id()); ?>"
data-base-price="<?php echo esc_attr($product->get_price()); ?>">
<h3>批量报价计算器</h3>
<p class="description">输入数量查看优惠价格</p>
<!-- 内容由JavaScript动态生成 -->
</div>
<?php
}
/**
* 显示动态价格范围
*/
public function display_dynamic_price_range($price_html, $product) {
if (is_admin() || !$product->is_type('simple')) {
return $price_html;
}
// 获取价格范围
$price_range = $this->get_price_range($product);
if ($price_range['min'] != $price_range['max']) {
$price_html = sprintf(
'<span class="price-range">%s - %s</span>',
wc_price($price_range['min']),
wc_price($price_range['max'])
);
$price_html .= '<small class="price-range-note">(价格随数量变化)</small>';
}
<?php
/**
* 前端价格显示模板
* 在产品页面显示动态价格计算器
*/
class SmartPricing_Frontend_Display {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
add_action('woocommerce_before_add_to_cart_button', array($this, 'display_pricing_calculator'));
add_filter('woocommerce_get_price_html', array($this, 'display_dynamic_price_range'), 10, 2);
}
/**
* 加载前端脚本和样式
*/
public function enqueue_frontend_scripts() {
if (!is_product()) {
return;
}
wp_enqueue_style(
'smart-pricing-frontend',
SMART_PRICING_PLUGIN_URL . 'assets/css/frontend.css',
array(),
SMART_PRICING_VERSION
);
wp_enqueue_script(
'smart-pricing-frontend',
SMART_PRICING_PLUGIN_URL . 'assets/js/frontend.js',
array('jquery'),
SMART_PRICING_VERSION,
true
);
global $product;
wp_localize_script('smart-pricing-frontend', 'smartPricing', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('smart_pricing_nonce'),
'product_id' => $product->get_id(),
'base_price' => $product->get_price(),
));
}
/**
* 显示价格计算器
*/
public function display_pricing_calculator() {
global $product;
if (!$product || !$product->is_purchasable()) {
return;
}
// 只对简单产品和变体产品显示
if (!$product->is_type('simple') && !$product->is_type('variable')) {
return;
}
?>
<div class="smart-pricing-calculator"
data-product-id="<?php echo esc_attr($product->get_id()); ?>"
data-base-price="<?php echo esc_attr($product->get_price()); ?>">
<h3>批量报价计算器</h3>
<p class="description">输入数量查看优惠价格</p>
<!-- 内容由JavaScript动态生成 -->
</div>
<?php
}
/**
* 显示动态价格范围
*/
public function display_dynamic_price_range($price_html, $product) {
if (is_admin() || !$product->is_type('simple')) {
return $price_html;
}
// 获取价格范围
$price_range = $this->get_price_range($product);
if ($price_range['min'] != $price_range['max']) {
$price_html = sprintf(
'<span class="price-range">%s - %s</span>',
wc_price($price_range['min']),
wc_price($price_range['max'])
);
$price_html .= '<small class="price-range-note">(价格随数量变化)</small>';
}


