文章目录[隐藏]
实现小批量动态定价的WordPress插件开发教程
概述
在电子商务网站中,动态定价策略是提升销售和利润的重要手段。本教程将指导您开发一个WordPress插件,实现基于购买数量的小批量动态定价功能。这个插件允许商家设置不同购买数量区间的价格,当顾客增加购买数量时,系统会自动显示相应的折扣价格。
插件功能规划
我们的动态定价插件将包含以下核心功能:
- 后台管理界面,用于设置不同产品的动态定价规则
- 前端产品页面显示动态价格表
- 购物车中实时更新价格
- 支持多种定价规则(数量区间、百分比折扣、固定折扣等)
创建插件基础结构
首先,我们需要创建插件的基本文件结构:
wp-content/plugins/
└── dynamic-bulk-pricing/
├── dynamic-bulk-pricing.php
├── includes/
│ ├── class-admin.php
│ ├── class-frontend.php
│ └── class-pricing-rules.php
├── assets/
│ ├── css/
│ │ └── admin-style.css
│ └── js/
│ └── frontend-script.js
└── templates/
└── pricing-table.php
主插件文件
创建主插件文件 dynamic-bulk-pricing.php:
<?php
/**
* Plugin Name: 小批量动态定价
* Plugin URI: https://yourwebsite.com/dynamic-bulk-pricing
* Description: 为WooCommerce产品添加基于购买数量的动态定价功能
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: dynamic-bulk-pricing
*/
// 防止直接访问
defined('ABSPATH') || exit;
// 定义插件常量
define('DBP_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('DBP_PLUGIN_URL', plugin_dir_url(__FILE__));
define('DBP_VERSION', '1.0.0');
// 检查WooCommerce是否激活
function dbp_check_woocommerce() {
if (!class_exists('WooCommerce')) {
add_action('admin_notices', function() {
?>
<div class="notice notice-error">
<p><?php _e('小批量动态定价插件需要WooCommerce才能正常工作。请安装并激活WooCommerce。', 'dynamic-bulk-pricing'); ?></p>
</div>
<?php
});
return false;
}
return true;
}
// 初始化插件
function dbp_init_plugin() {
if (!dbp_check_woocommerce()) {
return;
}
// 加载必要文件
require_once DBP_PLUGIN_PATH . 'includes/class-pricing-rules.php';
require_once DBP_PLUGIN_PATH . 'includes/class-admin.php';
require_once DBP_PLUGIN_PATH . 'includes/class-frontend.php';
// 初始化各个组件
DBP_Pricing_Rules::init();
DBP_Admin::init();
DBP_Frontend::init();
// 加载文本域
load_plugin_textdomain('dynamic-bulk-pricing', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
add_action('plugins_loaded', 'dbp_init_plugin');
// 插件激活时的操作
function dbp_activate_plugin() {
// 创建必要的数据库表
global $wpdb;
$table_name = $wpdb->prefix . 'dynamic_pricing_rules';
$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,
min_qty int(11) NOT NULL,
max_qty int(11) DEFAULT NULL,
discount_type varchar(20) NOT NULL,
discount_value decimal(10,2) NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY product_id (product_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 设置默认选项
add_option('dbp_version', DBP_VERSION);
}
register_activation_hook(__FILE__, 'dbp_activate_plugin');
// 插件停用时的清理操作
function dbp_deactivate_plugin() {
// 清理临时数据
delete_option('dbp_temp_data');
}
register_deactivation_hook(__FILE__, 'dbp_deactivate_plugin');
定价规则管理类
创建 includes/class-pricing-rules.php 文件,用于处理定价规则的数据操作:
<?php
/**
* 定价规则管理类
* 处理动态定价规则的CRUD操作
*/
class DBP_Pricing_Rules {
private static $table_name;
public static function init() {
global $wpdb;
self::$table_name = $wpdb->prefix . 'dynamic_pricing_rules';
}
/**
* 获取产品的定价规则
* @param int $product_id 产品ID
* @return array 定价规则数组
*/
public static function get_rules($product_id) {
global $wpdb;
$rules = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM " . self::$table_name . "
WHERE product_id = %d
ORDER BY min_qty ASC",
$product_id
),
ARRAY_A
);
return $rules ?: [];
}
/**
* 保存定价规则
* @param int $product_id 产品ID
* @param array $rules 规则数组
* @return bool 保存结果
*/
public static function save_rules($product_id, $rules) {
global $wpdb;
// 删除现有规则
self::delete_rules($product_id);
// 插入新规则
foreach ($rules as $rule) {
$wpdb->insert(
self::$table_name,
[
'product_id' => $product_id,
'min_qty' => intval($rule['min_qty']),
'max_qty' => !empty($rule['max_qty']) ? intval($rule['max_qty']) : NULL,
'discount_type' => sanitize_text_field($rule['discount_type']),
'discount_value' => floatval($rule['discount_value'])
],
['%d', '%d', '%d', '%s', '%f']
);
}
return true;
}
/**
* 删除产品的所有定价规则
* @param int $product_id 产品ID
* @return bool 删除结果
*/
public static function delete_rules($product_id) {
global $wpdb;
return $wpdb->delete(
self::$table_name,
['product_id' => $product_id],
['%d']
);
}
/**
* 根据数量计算折扣价格
* @param float $original_price 原价
* @param int $quantity 数量
* @param int $product_id 产品ID
* @return float 折扣后的价格
*/
public static function calculate_price($original_price, $quantity, $product_id) {
$rules = self::get_rules($product_id);
$discounted_price = $original_price;
foreach ($rules as $rule) {
$min_qty = intval($rule['min_qty']);
$max_qty = !empty($rule['max_qty']) ? intval($rule['max_qty']) : PHP_INT_MAX;
if ($quantity >= $min_qty && $quantity <= $max_qty) {
$discounted_price = self::apply_discount(
$original_price,
$rule['discount_type'],
$rule['discount_value']
);
break;
}
}
return $discounted_price;
}
/**
* 应用折扣
* @param float $price 原价
* @param string $type 折扣类型
* @param float $value 折扣值
* @return float 折扣后价格
*/
private static function apply_discount($price, $type, $value) {
switch ($type) {
case 'percentage':
// 百分比折扣
return $price * (1 - ($value / 100));
case 'fixed':
// 固定金额折扣
return max(0, $price - $value);
case 'fixed_price':
// 固定价格
return $value;
default:
return $price;
}
}
}
后台管理界面
创建 includes/class-admin.php 文件,用于添加产品编辑页面的定价规则设置:
<?php
/**
* 后台管理类
* 处理插件在WordPress后台的功能
*/
class DBP_Admin {
public static function init() {
// 在产品编辑页面添加定价规则选项卡
add_filter('woocommerce_product_data_tabs', [self::class, 'add_pricing_tab']);
// 在产品编辑页面添加定价规则面板
add_action('woocommerce_product_data_panels', [self::class, 'add_pricing_panel']);
// 保存定价规则
add_action('woocommerce_process_product_meta', [self::class, 'save_pricing_rules']);
// 加载管理样式和脚本
add_action('admin_enqueue_scripts', [self::class, 'enqueue_admin_assets']);
}
/**
* 添加定价规则选项卡
*/
public static function add_pricing_tab($tabs) {
$tabs['dynamic_pricing'] = [
'label' => __('动态定价', 'dynamic-bulk-pricing'),
'target' => 'dynamic_pricing_data',
'class' => ['show_if_simple', 'show_if_variable'],
'priority' => 80
];
return $tabs;
}
/**
* 添加定价规则面板
*/
public static function add_pricing_panel() {
global $post;
$rules = DBP_Pricing_Rules::get_rules($post->ID);
?>
<div id="dynamic_pricing_data" class="panel woocommerce_options_panel">
<div class="options_group">
<h3><?php _e('小批量动态定价规则', 'dynamic-bulk-pricing'); ?></h3>
<p class="description">
<?php _e('设置不同购买数量区间的价格规则。数量范围留空表示无上限。', 'dynamic-bulk-pricing'); ?>
</p>
<div id="dynamic-pricing-rules-container">
<?php if (empty($rules)): ?>
<div class="pricing-rule-row" data-index="0">
<div class="rule-fields">
<p class="form-field">
<label for="min_qty_0"><?php _e('最小数量', 'dynamic-bulk-pricing'); ?></label>
<input type="number"
name="dynamic_pricing_rules[0][min_qty]"
id="min_qty_0"
class="short"
min="1"
value="1"
required>
</p>
<p class="form-field">
<label for="max_qty_0"><?php _e('最大数量', 'dynamic-bulk-pricing'); ?></label>
<input type="number"
name="dynamic_pricing_rules[0][max_qty]"
id="max_qty_0"
class="short"
min="1"
placeholder="<?php _e('留空表示无上限', 'dynamic-bulk-pricing'); ?>">
</p>
<p class="form-field">
<label for="discount_type_0"><?php _e('折扣类型', 'dynamic-bulk-pricing'); ?></label>
<select name="dynamic_pricing_rules[0][discount_type]"
id="discount_type_0"
class="select short">
<option value="percentage"><?php _e('百分比折扣', 'dynamic-bulk-pricing'); ?></option>
<option value="fixed"><?php _e('固定金额折扣', 'dynamic-bulk-pricing'); ?></option>
<option value="fixed_price"><?php _e('固定价格', 'dynamic-bulk-pricing'); ?></option>
</select>
</p>
<p class="form-field">
<label for="discount_value_0"><?php _e('折扣值', 'dynamic-bulk-pricing'); ?></label>
<input type="number"
name="dynamic_pricing_rules[0][discount_value]"
id="discount_value_0"
class="short wc_input_price"
step="0.01"
min="0"
value="0">
<span class="description discount-value-desc">
<?php _e('百分比折扣请输入百分比数字(如10表示10%折扣)', 'dynamic-bulk-pricing'); ?>
</span>
</p>
<button type="button" class="button remove-rule"><?php _e('删除规则', 'dynamic-bulk-pricing'); ?></button>
</div>
</div>
<?php else: ?>
<?php foreach ($rules as $index => $rule): ?>
<div class="pricing-rule-row" data-index="<?php echo $index; ?>">
<div class="rule-fields">
<!-- 规则字段代码类似上面,此处省略以节省篇幅 -->
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<button type="button" id="add-pricing-rule" class="button">
<?php _e('添加定价规则', 'dynamic-bulk-pricing'); ?>
</button>
</div>
</div>
<?php
}
/**
* 保存定价规则
*/
public static function save_pricing_rules($product_id) {
if (isset($_POST['dynamic_pricing_rules']) && is_array($_POST['dynamic_pricing_rules'])) {
$rules = [];
foreach ($_POST['dynamic_pricing_rules'] as $rule_data) {
if (!empty($rule_data['min_qty'])) {
$rules[] = [
'min_qty' => intval($rule_data['min_qty']),
'max_qty' => !empty($rule_data['max_qty']) ? intval($rule_data['max_qty']) : '',
'discount_type' => sanitize_text_field($rule_data['discount_type']),
'discount_value' => floatval($rule_data['discount_value'])
];
}
}
// 按最小数量排序
usort($rules, function($a, $b) {
return $a['min_qty'] - $b['min_qty'];
});
DBP_Pricing_Rules::save_rules($product_id, $rules);
}
}
/**
* 加载管理资源
*/
public static function enqueue_admin_assets($hook) {
if ('post.php' !== $hook && 'post-new.php' !== $hook) {
return;
}
wp_enqueue_style(
'dbp-admin-style',
DBP_PLUGIN_URL . 'assets/css/admin-style.css',
[],
DBP_VERSION
);
wp_enqueue_script(
'dbp-admin-script',
DBP_PLUGIN_URL . 'assets/js/admin-script.js',
['jquery'],
DBP_VERSION,
true
);
wp_localize_script('dbp-admin-script', 'dbp_admin', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('dbp_admin_nonce'),
'i18n' => [
'confirm_delete' => __('确定要删除这条规则吗?', 'dynamic-bulk-pricing')
]
]);
}
}
前端显示与交互
创建 includes/class-frontend.php 文件,处理前端价格显示和计算:
<?php
/**
* 前端显示类
* 处理插件在前端的功能
*/
class DBP_Frontend {
public static function init() {
// 在产品页面显示动态价格表
add_action('woocommerce_single_product_summary', [self::class, 'display_pricing_table'], 25);
// 动态更新价格显示
add_filter('woocommerce_get_price_html', [self::class, 'update_price_display'], 10, 2);
// 购物车价格计算
add_action('woocommerce_before_calculate_totals', [self::class, 'update_cart_prices']);
// 加载前端脚本
add_action('wp_enqueue_scripts', [self::class, 'enqueue_frontend_assets']);
// AJAX处理价格计算
add_action('wp_ajax_dbp_calculate_price', [self::class, 'ajax_calculate_price']);
add_action('wp_ajax_nopriv_dbp_calculate_price', [self::class, 'ajax_calculate_price']);
}
/**
* 显示动态价格表
*/
public static function display_pricing_table() {
global $product;
if (!$product || !$product->is_type('simple')) {
return;
}
$rules = DBP_Pricing_Rules::get_rules($product->get_id());
if (empty($rules)) {
return;
}
// 获取模板
$template_path = DBP_PLUGIN_PATH . 'templates/pricing-table.php';
if (file_exists($template_path)) {
include $template_path;
} else {
// 默认表格显示
?>
<div class="dynamic-pricing-table">
<h3><?php _e('批量购买优惠', 'dynamic-bulk-pricing'); ?></h3>
<table class="pricing-table">
<thead>
<tr>
<th><?php _e('购买数量', 'dynamic-bulk-pricing'); ?></th>
<th><?php _e('单价', 'dynamic-bulk-pricing'); ?></th>
<th><?php _e('节省金额', 'dynamic-bulk-pricing'); ?></th>
</tr>
</thead>
<tbody>
<?php
$original_price = $product->get_regular_price();
$current_price = $product->get_price();
foreach ($rules as $rule):
$discounted_price = DBP_Pricing_Rules::calculate_price(
$original_price,
$rule['min_qty'],
$product->get_id()
);
$savings = $original_price - $discounted_price;
$range_text = $rule['min_qty'];
$range_text .= !empty($rule['max_qty']) ? ' - ' . $rule['max_qty'] : '+';
?>
<tr>
<td><?php echo esc_html($range_text); ?></td>
<td><?php echo wc_price($discounted_price); ?></td>
<td class="savings"><?php echo wc_price($savings); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
}
/**
* 更新价格显示
*/
public static function update_price_display($price_html, $product) {
// 只在产品页面且是简单产品时处理
if (!is_product() || !$product->is_type('simple')) {
return $price_html;
}
// 添加动态价格容器
$price_html .= '<div class="dynamic-price-container"
data-product-id="' . esc_attr($product->get_id()) . '"
data-original-price="' . esc_attr($product->get_regular_price()) . '">
<span class="dynamic-price-display"></span>
</div>';
return $price_html;
}
/**
* 更新购物车价格
*/
public static function update_cart_prices($cart) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
$quantity = $cart_item['quantity'];
// 获取产品对象
$product = wc_get_product($product_id);
if (!$product) {
continue;
}
// 计算动态价格
$original_price = $product->get_regular_price();
$dynamic_price = DBP_Pricing_Rules::calculate_price(
$original_price,
$quantity,
$product_id
);
// 如果计算出的价格与原价不同,则更新
if ($dynamic_price != $original_price) {
$cart_item['data']->set_price($dynamic_price);
}
}
}
/**
* AJAX计算价格
*/
public static function ajax_calculate_price() {
// 验证nonce
if (!check_ajax_referer('dbp_frontend_nonce', 'nonce', false)) {
wp_die('Security check failed');
}
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity']);
$product = wc_get_product($product_id);
if (!$product) {
wp_send_json_error(['message' => 'Product not found']);
}
$original_price = $product->get_regular_price();
$dynamic_price = DBP_Pricing_Rules::calculate_price(
$original_price,
$quantity,
$product_id
);
wp_send_json_success([
'price' => $dynamic_price,
'price_display' => wc_price($dynamic_price),
'savings' => $original_price - $dynamic_price,
'savings_display' => wc_price($original_price - $dynamic_price)
]);
}
/**
* 加载前端资源
*/
public static function enqueue_frontend_assets() {
if (!is_product()) {
return;
}
wp_enqueue_script(
'dbp-frontend-script',
DBP_PLUGIN_URL . 'assets/js/frontend-script.js',
['jquery', 'wc-add-to-cart-variation'],
DBP_VERSION,
true
);
wp_localize_script('dbp-frontend-script', 'dbp_frontend', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('dbp_frontend_nonce')
]);
wp_enqueue_style(
'dbp-frontend-style',
DBP_PLUGIN_URL . 'assets/css/frontend-style.css',
[],
DBP_VERSION
);
}
}
前端JavaScript文件
创建 assets/js/frontend-script.js 文件,处理前端交互:
/**
* 小批量动态定价前端脚本
* 处理数量变化时的价格实时计算
*/
(function($) {
'use strict';
$(document).ready(function() {
// 初始化动态定价功能
initDynamicPricing();
// 监听数量输入框变化
$(document).on('change input', '.quantity input.qty', function() {
updateDynamicPrice($(this));
});
// 监听数量增减按钮
$(document).on('click', '.quantity .plus, .quantity .minus', function() {
setTimeout(function() {
var $input = $('.quantity input.qty');
updateDynamicPrice($input);
}, 100);
});
});
/**
* 初始化动态定价
*/
function initDynamicPricing() {
var $container = $('.dynamic-price-container');
if ($container.length === 0) {
return;
}
var $quantityInput = $('.quantity input.qty');
if ($quantityInput.length > 0) {
updateDynamicPrice($quantityInput);
}
}
/**
* 更新动态价格显示
*/
function updateDynamicPrice($input) {
var quantity = parseInt($input.val());
if (isNaN(quantity) || quantity < 1) {
quantity = 1;
}
var $container = $('.dynamic-price-container');
var productId = $container.data('product-id');
// 显示加载状态
$container.find('.dynamic-price-display').html(
'<span class="loading">' + dbp_frontend.i18n.calculating + '</span>'
);
// 发送AJAX请求
$.ajax({
url: dbp_frontend.ajax_url,
type: 'POST',
data: {
action: 'dbp_calculate_price',
product_id: productId,
quantity: quantity,
nonce: dbp_frontend.nonce
},
success: function(response) {
if (response.success) {
var data = response.data;
var html = '<div class="dynamic-price-info">';
html += '<strong>' + dbp_frontend.i18n.unit_price + ':</strong> ' + data.price_display;
if (data.savings > 0) {
html += '<br><span class="savings">';
html += '<strong>' + dbp_frontend.i18n.savings + ':</strong> ' + data.savings_display;
html += '</span>';
}
html += '</div>';
$container.find('.dynamic-price-display').html(html);
}
},
error: function() {
$container.find('.dynamic-price-display').html(
'<span class="error">' + dbp_frontend.i18n.calculation_error + '</span>'
);
}
});
}
// 添加本地化字符串
if (typeof dbp_frontend === 'undefined') {
dbp_frontend = {
i18n: {
calculating: '计算中...',
unit_price: '单价',
savings: '节省',
calculation_error: '价格计算失败'
}
};
}
})(jQuery);
前端样式文件
创建 assets/css/frontend-style.css 文件:
/**
* 小批量动态定价前端样式
*/
/* 动态价格表格 */
.dynamic-pricing-table {
margin: 20px 0;
padding: 15px;
background: #f8f8f8;
border: 1px solid #e5e5e5;
border-radius: 4px;
}
.dynamic-pricing-table h3 {
margin-top: 0;
margin-bottom: 15px;
color: #333;
font-size: 18px;
}
.pricing-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 10px;
}
.pricing-table th {
background: #2c3e50;
color: white;
padding: 10px;
text-align: left;
font-weight: 600;
}
.pricing-table td {
padding: 10px;
border-bottom: 1px solid #ddd;
}
.pricing-table tr:nth-child(even) {
background: #f9f9f9;
}
.pricing-table tr:hover {
background: #f0f0f0;
}
.pricing-table .savings {
color: #27ae60;
font-weight: bold;
}
/* 动态价格显示容器 */
.dynamic-price-container {
margin-top: 10px;
padding: 10px;
background: #f0f8ff;
border: 1px solid #d1e7ff;
border-radius: 4px;
}
.dynamic-price-info {
font-size: 14px;
line-height: 1.5;
}
.dynamic-price-info .savings {
color: #27ae60;
font-weight: bold;
}
.dynamic-price-info .loading {
color: #666;
font-style: italic;
}
.dynamic-price-info .error {
color: #e74c3c;
}
/* 响应式设计 */
@media (max-width: 768px) {
.pricing-table {
display: block;
overflow-x: auto;
}
.dynamic-pricing-table {
padding: 10px;
}
.pricing-table th,
.pricing-table td {
padding: 8px 5px;
font-size: 13px;
}
}
模板文件
创建 templates/pricing-table.php 文件:
<?php
/**
* 动态价格表格模板
*
* @var array $rules 定价规则数组
* @var WC_Product $product 产品对象
*/
if (!defined('ABSPATH')) {
exit;
}
global $product;
$original_price = $product->get_regular_price();
?>
<div class="dynamic-pricing-table">
<h3><?php echo esc_html__('批量购买优惠', 'dynamic-bulk-pricing'); ?></h3>
<?php if (!empty($rules)): ?>
<div class="pricing-info">
<p><?php echo esc_html__('购买越多,单价越优惠!', 'dynamic-bulk-pricing'); ?></p>
</div>
<table class="pricing-table">
<thead>
<tr>
<th><?php echo esc_html__('购买数量', 'dynamic-bulk-pricing'); ?></th>
<th><?php echo esc_html__('单价', 'dynamic-bulk-pricing'); ?></th>
<th><?php echo esc_html__('节省金额', 'dynamic-bulk-pricing'); ?></th>
<th><?php echo esc_html__('折扣率', 'dynamic-bulk-pricing'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($rules as $index => $rule): ?>
<?php
$min_qty = intval($rule['min_qty']);
$max_qty = !empty($rule['max_qty']) ? intval($rule['max_qty']) : null;
// 计算折扣价格
$discounted_price = DBP_Pricing_Rules::calculate_price(
$original_price,
$min_qty,
$product->get_id()
);
// 计算节省金额
$savings = $original_price - $discounted_price;
// 计算折扣率
$discount_rate = $original_price > 0 ?
round(($savings / $original_price) * 100, 1) : 0;
// 生成数量范围文本
$range_text = $min_qty;
if ($max_qty) {
$range_text .= ' - ' . $max_qty;
} else {
$range_text .= '+';
}
?>
<tr class="pricing-tier tier-<?php echo esc_attr($index + 1); ?>">
<td class="quantity-range">
<strong><?php echo esc_html($range_text); ?></strong>
</td>
<td class="unit-price">
<span class="price"><?php echo wc_price($discounted_price); ?></span>
</td>
<td class="savings">
<span class="savings-amount"><?php echo wc_price($savings); ?></span>
</td>
<td class="discount-rate">
<span class="rate-badge">-<?php echo esc_html($discount_rate); ?>%</span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="pricing-note">
<p><small><?php echo esc_html__('* 价格根据购买数量自动计算,加入购物车后生效', 'dynamic-bulk-pricing'); ?></small></p>
</div>
<?php else: ?>
<p><?php echo esc_html__('暂无动态定价规则', 'dynamic-bulk-pricing'); ?></p>
<?php endif; ?>
</div>
插件配置与优化
添加多语言支持
创建语言文件目录和基础翻译文件:
// 在插件主文件中添加语言加载
load_plugin_textdomain('dynamic-bulk-pricing', false, dirname(plugin_basename(__FILE__)) . '/languages/');
添加短代码支持
在 includes/class-frontend.php 中添加短代码功能:
/**
* 添加短代码支持
*/
public static function add_shortcodes() {
add_shortcode('dynamic_pricing_table', [self::class, 'pricing_table_shortcode']);
}
/**
* 定价表格短代码
*/
public static function pricing_table_shortcode($atts) {
$atts = shortcode_atts([
'product_id' => 0,
], $atts, 'dynamic_pricing_table');
$product_id = intval($atts['product_id']);
if (!$product_id && is_product()) {
global $product;
$product_id = $product->get_id();
}
if (!$product_id) {
return '';
}
ob_start();
self::display_pricing_table_for_product($product_id);
return ob_get_clean();
}
/**
* 为指定产品显示定价表格
*/
private static function display_pricing_table_for_product($product_id) {
$product = wc_get_product($product_id);
if (!$product) {
return;
}
$rules = DBP_Pricing_Rules::get_rules($product_id);
if (empty($rules)) {
return;
}
// 加载模板
$template_path = DBP_PLUGIN_PATH . 'templates/pricing-table.php';
if (file_exists($template_path)) {
include $template_path;
}
}
测试与部署
测试步骤
- 安装与激活:将插件文件夹上传到WordPress的插件目录,在后台激活插件。
- 创建测试产品:在WooCommerce中添加一个简单产品,设置常规价格。
-
配置定价规则:在产品编辑页面的"动态定价"选项卡中,添加多个定价规则:
- 1-10件:原价
- 11-50件:10%折扣
- 51-100件:15%折扣
- 101件以上:20%折扣
-
前端测试:
- 访问产品页面,查看动态价格表格是否显示
- 调整数量输入框,观察价格是否实时更新
- 将产品加入购物车,验证价格是否正确应用
-
功能验证:
- 测试不同数量区间的价格计算
- 验证购物车中的价格更新
- 测试AJAX价格计算的响应
性能优化建议
- 缓存策略:对频繁查询的定价规则添加缓存
- 数据库优化:为定价规则表添加合适的索引
- 懒加载:对非关键资源使用懒加载
- CDN支持:将静态资源托管到CDN
总结
通过本教程,我们成功开发了一个功能完整的小批量动态定价WordPress插件。该插件具有以下特点:
- 易用性:通过直观的后台界面管理定价规则
- 实时性:前端实时计算并显示动态价格
- 灵活性:支持多种折扣类型和数量区间
- 兼容性:与WooCommerce完美集成
- 可扩展性:模块化设计便于功能扩展
这个插件可以帮助电商网站实施灵活的定价策略,提高客户购买量和平均订单价值。您可以根据实际需求进一步扩展功能,如添加会员专属定价、限时折扣、区域定价等高级功能。
记得在实际部署前进行充分测试,并根据您的具体业务需求调整代码逻辑。祝您开发顺利!
