文章目录[隐藏]
WordPress文创产品柔性定价插件开发指南
引言:文创产品的定价挑战
在文创产品销售领域,定价策略往往比普通商品更加复杂。一件手工艺品、数字艺术品或文创衍生品的价值不仅取决于成本,还受到设计独特性、创作者知名度、限量程度、市场需求等多种因素影响。传统的固定定价模式难以适应这种多样性,因此开发一个能够实现柔性定价的WordPress插件变得尤为重要。
本文将详细介绍如何开发一个功能完整的WordPress文创产品柔性定价插件,帮助文创创作者和商家根据多种因素动态调整产品价格。
插件架构设计
1.1 插件基础结构
首先,我们创建插件的基本文件结构:
wp-content/plugins/flexible-pricing/
├── flexible-pricing.php # 主插件文件
├── includes/
│ ├── class-price-calculator.php # 价格计算核心类
│ ├── class-admin-settings.php # 后台设置类
│ └── class-frontend-display.php # 前端显示类
├── assets/
│ ├── css/
│ │ └── admin-style.css # 后台样式
│ └── js/
│ └── frontend-script.js # 前端脚本
└── templates/
└── price-display.php # 价格显示模板
1.2 主插件文件
<?php
/**
* Plugin Name: 文创产品柔性定价
* Plugin URI: https://example.com/flexible-pricing
* Description: 为WordPress文创产品提供灵活的定价解决方案
* Version: 1.0.0
* Author: 文创开发者
* License: GPL v2 or later
* Text Domain: flexible-pricing
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('FLEXIBLE_PRICING_VERSION', '1.0.0');
define('FLEXIBLE_PRICING_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FLEXIBLE_PRICING_PLUGIN_URL', plugin_dir_url(__FILE__));
// 自动加载类文件
spl_autoload_register(function ($class) {
$prefix = 'FlexiblePricing\';
$base_dir = FLEXIBLE_PRICING_PLUGIN_DIR . 'includes/';
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
$relative_class = substr($class, $len);
$file = $base_dir . str_replace('\', '/', $relative_class) . '.php';
if (file_exists($file)) {
require $file;
}
});
// 初始化插件
add_action('plugins_loaded', 'flexible_pricing_init');
function flexible_pricing_init() {
// 检查WooCommerce是否激活(如果依赖WooCommerce)
if (!class_exists('WooCommerce')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>';
echo __('文创产品柔性定价插件需要WooCommerce支持。', 'flexible-pricing');
echo '</p></div>';
});
return;
}
// 初始化核心类
$price_calculator = new FlexiblePricingPriceCalculator();
$admin_settings = new FlexiblePricingAdminSettings();
$frontend_display = new FlexiblePricingFrontendDisplay();
// 注册激活和停用钩子
register_activation_hook(__FILE__, 'flexible_pricing_activate');
register_deactivation_hook(__FILE__, 'flexible_pricing_deactivate');
}
function flexible_pricing_activate() {
// 创建必要的数据库表
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'flexible_pricing_rules';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
product_id bigint(20) NOT NULL,
rule_type varchar(50) NOT NULL,
rule_condition text NOT NULL,
adjustment_type varchar(20) NOT NULL,
adjustment_value decimal(10,2) NOT NULL,
priority int(11) DEFAULT 0,
is_active tinyint(1) DEFAULT 1,
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('flexible_pricing_version', FLEXIBLE_PRICING_VERSION);
}
function flexible_pricing_deactivate() {
// 清理临时数据
wp_clear_scheduled_hook('flexible_pricing_daily_tasks');
}
价格计算引擎开发
2.1 价格计算核心类
<?php
namespace FlexiblePricing;
/**
* 价格计算引擎
* 处理所有定价规则和计算逻辑
*/
class PriceCalculator {
private $rules = [];
public function __construct() {
add_filter('woocommerce_product_get_price', [$this, 'calculate_flexible_price'], 10, 2);
add_filter('woocommerce_product_variation_get_price', [$this, 'calculate_flexible_price'], 10, 2);
}
/**
* 计算柔性价格
* @param float $price 原始价格
* @param WC_Product $product 产品对象
* @return float 计算后的价格
*/
public function calculate_flexible_price($price, $product) {
// 获取产品ID
$product_id = $product->get_id();
// 获取适用的定价规则
$rules = $this->get_applicable_rules($product_id);
// 如果没有规则,返回原价
if (empty($rules)) {
return $price;
}
// 按优先级排序
usort($rules, function($a, $b) {
return $b['priority'] - $a['priority'];
});
// 应用规则
$final_price = $price;
foreach ($rules as $rule) {
if ($this->check_rule_condition($rule, $product)) {
$final_price = $this->apply_price_adjustment($final_price, $rule);
}
}
return max(0, $final_price); // 确保价格不为负
}
/**
* 获取适用的定价规则
* @param int $product_id 产品ID
* @return array 规则数组
*/
private function get_applicable_rules($product_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'flexible_pricing_rules';
$rules = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name
WHERE (product_id = %d OR product_id = 0)
AND is_active = 1
ORDER BY priority DESC",
$product_id
),
ARRAY_A
);
return $rules;
}
/**
* 检查规则条件
* @param array $rule 规则数据
* @param WC_Product $product 产品对象
* @return bool 是否满足条件
*/
private function check_rule_condition($rule, $product) {
$condition = json_decode($rule['rule_condition'], true);
if (!$condition) {
return false;
}
// 检查用户角色条件
if (isset($condition['user_role'])) {
$user = wp_get_current_user();
if (!in_array($condition['user_role'], $user->roles)) {
return false;
}
}
// 检查购买数量条件
if (isset($condition['min_quantity'])) {
$cart = WC()->cart;
if ($cart) {
$quantity = $this->get_cart_item_quantity($product->get_id());
if ($quantity < $condition['min_quantity']) {
return false;
}
}
}
// 检查日期范围条件
if (isset($condition['date_range'])) {
$current_time = current_time('timestamp');
$start_time = strtotime($condition['date_range']['start']);
$end_time = strtotime($condition['date_range']['end']);
if ($current_time < $start_time || $current_time > $end_time) {
return false;
}
}
return true;
}
/**
* 应用价格调整
* @param float $price 当前价格
* @param array $rule 规则数据
* @return float 调整后的价格
*/
private function apply_price_adjustment($price, $rule) {
$adjustment_type = $rule['adjustment_type'];
$adjustment_value = floatval($rule['adjustment_value']);
switch ($adjustment_type) {
case 'fixed_increase':
return $price + $adjustment_value;
case 'fixed_decrease':
return $price - $adjustment_value;
case 'percentage_increase':
return $price * (1 + $adjustment_value / 100);
case 'percentage_decrease':
return $price * (1 - $adjustment_value / 100);
case 'fixed_price':
return $adjustment_value;
default:
return $price;
}
}
/**
* 获取购物车中商品数量
* @param int $product_id 产品ID
* @return int 数量
*/
private function get_cart_item_quantity($product_id) {
$cart = WC()->cart;
if (!$cart) {
return 0;
}
foreach ($cart->get_cart() as $cart_item) {
if ($cart_item['product_id'] == $product_id) {
return $cart_item['quantity'];
}
}
return 0;
}
}
后台管理界面
3.1 定价规则管理
<?php
namespace FlexiblePricing;
/**
* 后台管理设置
*/
class AdminSettings {
public function __construct() {
add_action('admin_menu', [$this, 'add_admin_menu']);
add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
add_action('add_meta_boxes', [$this, 'add_product_meta_box']);
add_action('save_post_product', [$this, 'save_product_pricing_rules']);
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_submenu_page(
'woocommerce',
__('柔性定价规则', 'flexible-pricing'),
__('柔性定价', 'flexible-pricing'),
'manage_options',
'flexible-pricing-rules',
[$this, 'render_rules_page']
);
}
/**
* 渲染规则管理页面
*/
public function render_rules_page() {
?>
<div class="wrap">
<h1><?php echo esc_html__('文创产品柔性定价规则', 'flexible-pricing'); ?></h1>
<div id="flexible-pricing-rules-app">
<!-- Vue.js应用容器 -->
<div class="card">
<h2><?php echo esc_html__('添加新规则', 'flexible-pricing'); ?></h2>
<form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
<input type="hidden" name="action" value="save_flexible_pricing_rule">
<?php wp_nonce_field('save_flexible_pricing_rule'); ?>
<table class="form-table">
<tr>
<th scope="row">
<label for="product_id"><?php echo esc_html__('适用产品', 'flexible-pricing'); ?></label>
</th>
<td>
<select name="product_id" id="product_id" class="regular-text">
<option value="0"><?php echo esc_html__('所有产品', 'flexible-pricing'); ?></option>
<?php
$products = wc_get_products(['limit' => -1]);
foreach ($products as $product) {
echo '<option value="' . esc_attr($product->get_id()) . '">';
echo esc_html($product->get_name());
echo '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th scope="row">
<label for="rule_type"><?php echo esc_html__('规则类型', 'flexible-pricing'); ?></label>
</th>
<td>
<select name="rule_type" id="rule_type" class="regular-text">
<option value="user_role"><?php echo esc_html__('用户角色', 'flexible-pricing'); ?></option>
<option value="quantity"><?php echo esc_html__('购买数量', 'flexible-pricing'); ?></option>
<option value="date_range"><?php echo esc_html__('日期范围', 'flexible-pricing'); ?></option>
<option value="custom"><?php echo esc_html__('自定义条件', 'flexible-pricing'); ?></option>
</select>
</td>
</tr>
<tr>
<th scope="row">
<label for="adjustment_type"><?php echo esc_html__('调整类型', 'flexible-pricing'); ?></label>
</th>
<td>
<select name="adjustment_type" id="adjustment_type" class="regular-text">
<option value="percentage_increase"><?php echo esc_html__('百分比增加', 'flexible-pricing'); ?></option>
<option value="percentage_decrease"><?php echo esc_html__('百分比减少', 'flexible-pricing'); ?></option>
<option value="fixed_increase"><?php echo esc_html__('固定金额增加', 'flexible-pricing'); ?></option>
<option value="fixed_decrease"><?php echo esc_html__('固定金额减少', 'flexible-pricing'); ?></option>
<option value="fixed_price"><?php echo esc_html__('固定价格', 'flexible-pricing'); ?></option>
</select>
</td>
</tr>
<tr>
<th scope="row">
<label for="adjustment_value"><?php echo esc_html__('调整值', 'flexible-pricing'); ?></label>
</th>
<td>
<input type="number"
name="adjustment_value"
id="adjustment_value"
step="0.01"
class="regular-text"
required>
</td>
</tr>
<tr>
<th scope="row">
<label for="priority"><?php echo esc_html__('优先级', 'flexible-pricing'); ?></label>
</th>
<td>
<input type="number"
name="priority"
id="priority"
value="0"
class="small-text">
<p class="description"><?php echo esc_html__('数字越大优先级越高', 'flexible-pricing'); ?></p>
</td>
</tr>
</table>
<?php submit_button(__('保存规则', 'flexible-pricing')); ?>
</form>
</div>
<!-- 现有规则列表 -->
<div class="card">
<h2><?php echo esc_html__('现有定价规则', 'flexible-pricing'); ?></h2>
<?php $this->render_rules_table(); ?>
</div>
</div>
</div>
<?php
}
/**
* 渲染规则表格
*/
private function render_rules_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'flexible_pricing_rules';
$rules = $wpdb->get_results("SELECT * FROM $table_name ORDER BY priority DESC, id DESC");
if (empty($rules)) {
echo '<p>' . esc_html__('暂无定价规则。', 'flexible-pricing') . '</p>';
return;
}
echo '<table class="wp-list-table widefat fixed striped">';
echo '<thead>';
echo '<tr>';
echo '<th>' . esc_html__('ID', 'flexible-pricing') . '</th>';
echo '<th>' . esc_html__('产品', 'flexible-pricing') . '</th>';
echo '<th>' . esc_html__('规则类型', 'flexible-pricing') . '</th>';
echo '<th>' . esc_html__('调整方式', 'flexible-pricing') . '</th>';
echo '<th>' . esc_html__('调整值', 'flexible-pricing') . '</th>';
echo '<th>' . esc_html__('优先级', 'flexible-pricing') . '</th>';
echo '<th>' . esc_html__('操作', 'flexible-pricing') . '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
foreach ($rules as $rule) {
$product_name = $rule->product_id == 0
? __('所有产品', 'flexible-pricing')
: get_the_title($rule->product_id);
echo '<tr>';
echo '<td>' . esc_html($rule->id) . '</td>';
echo '<td>' . esc_html($product_name) . '</td>';
echo '<td>' . esc_html($this->get_rule_type_label($rule->rule_type)) . '</td>';
echo '<td>' . esc_html($this->get_adjustment_type_label($rule->adjustment_type)) . '</td>';
echo '<td>' . esc_html($rule->adjustment_value) . '</td>';
echo '<td>' . esc_html($rule->priority) . '</td>';
echo '<td>';
echo '<a href="' . esc_url(wp_nonce_url(
admin_url('admin-post.php?action=delete_flexible_pricing_rule&rule_id=' . $rule->id),
'delete_flexible_pricing_rule'
)) . '" class="button button-small" onclick="return confirm('' . esc_js(__('确定要删除此规则吗?', 'flexible-pricing')) . '')">' . __('删除', 'flexible-pricing') . '</a>';
echo '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
}
/**
* 获取规则类型标签
*/
private function get_rule_type_label($type) {
$labels = [
'user_role' => __('用户角色', 'flexible-pricing'),
'quantity' => __('购买数量', 'flexible-pricing'),
'date_range' => __('日期范围', 'flexible-pricing'),
'custom' => __('自定义', 'flexible-pricing')
];
return $labels[$type] ?? $type;
}
/**
* 获取调整类型标签
*/
private function get_adjustment_type_label($type) {
$labels = [
'percentage_increase' => __('百分比增加', 'flexible-pricing'),
'percentage_decrease' => __('百分比减少', 'flexible-pricing'),
'fixed_increase' => __('固定增加', 'flexible-pricing'),
'fixed_decrease' => __('固定减少', 'flexible-pricing'),
'fixed_price' => __('固定价格', 'flexible-pricing')
];
return $labels[$type] ?? $type;
}
/**
* 添加产品编辑页面的定价规则元框
*/
public function add_product_meta_box() {
add_meta_box(
'flexible_pricing_rules',
__('柔性定价规则', 'flexible-pricing'),
[$this, 'render_product_pricing_meta_box'],
'product',
'side',
'high'
);
}
/**
* 渲染产品定价规则元框
*/
public function render_product_pricing_meta_box($post) {
$product_id = $post->ID;
$rules = $this->get_product_rules($product_id);
echo '<div class="flexible-pricing-product-rules">';
if (empty($rules)) {
echo '<p>' . __('暂无特定定价规则。', 'flexible-pricing') . '</p>';
} else {
echo '<ul>';
foreach ($rules as $rule) {
echo '<li>' . esc_html($this->format_rule_description($rule)) . '</li>';
}
echo '</ul>';
}
echo '<p>';
echo '<a href="' . admin_url('admin.php?page=flexible-pricing-rules&product_id=' . $product_id) . '" class="button">';
echo __('管理定价规则', 'flexible-pricing');
echo '</a>';
echo '</p>';
echo '</div>';
}
/**
* 保存产品定价规则
*/
public function save_product_pricing_rules($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (!current_user_can('edit_product', $post_id)) {
return;
}
// 这里可以添加保存产品特定规则的逻辑
}
/**
* 获取产品规则
*/
private function get_product_rules($product_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'flexible_pricing_rules';
return $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name WHERE product_id = %d AND is_active = 1",
$product_id
)
);
}
/**
* 格式化规则描述
*/
private function format_rule_description($rule) {
$condition = json_decode($rule->rule_condition, true);
$description = '';
switch ($rule->rule_type) {
case 'user_role':
$description = sprintf(
__('用户角色: %s', 'flexible-pricing'),
$condition['user_role'] ?? ''
);
break;
case 'quantity':
$description = sprintf(
__('购买数量 ≥ %d', 'flexible-pricing'),
$condition['min_quantity'] ?? 0
);
break;
case 'date_range':
$description = sprintf(
__('日期范围: %s 至 %s', 'flexible-pricing'),
$condition['date_range']['start'] ?? '',
$condition['date_range']['end'] ?? ''
);
break;
}
$adjustment = $this->format_adjustment_description($rule);
return $description . ' → ' . $adjustment;
}
/**
* 格式化调整描述
*/
private function format_adjustment_description($rule) {
switch ($rule->adjustment_type) {
case 'percentage_increase':
return sprintf(__('价格增加 %s%%', 'flexible-pricing'), $rule->adjustment_value);
case 'percentage_decrease':
return sprintf(__('价格减少 %s%%', 'flexible-pricing'), $rule->adjustment_value);
case 'fixed_increase':
return sprintf(__('价格增加 %s元', 'flexible-pricing'), $rule->adjustment_value);
case 'fixed_decrease':
return sprintf(__('价格减少 %s元', 'flexible-pricing'), $rule->adjustment_value);
case 'fixed_price':
return sprintf(__('固定价格 %s元', 'flexible-pricing'), $rule->adjustment_value);
default:
return $rule->adjustment_type;
}
}
/**
* 加载后台脚本和样式
*/
public function enqueue_admin_scripts($hook) {
if ($hook === 'woocommerce_page_flexible-pricing-rules' || $hook === 'post.php') {
wp_enqueue_style(
'flexible-pricing-admin',
FLEXIBLE_PRICING_PLUGIN_URL . 'assets/css/admin-style.css',
[],
FLEXIBLE_PRICING_VERSION
);
wp_enqueue_script(
'flexible-pricing-admin',
FLEXIBLE_PRICING_PLUGIN_URL . 'assets/js/admin-script.js',
['jquery', 'jquery-ui-datepicker'],
FLEXIBLE_PRICING_VERSION,
true
);
wp_localize_script('flexible-pricing-admin', 'flexiblePricingAdmin', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('flexible_pricing_admin_nonce'),
'i18n' => [
'confirm_delete' => __('确定要删除此规则吗?', 'flexible-pricing'),
'saving' => __('保存中...', 'flexible-pricing'),
'saved' => __('保存成功!', 'flexible-pricing')
]
]);
}
}
}
## 前端价格显示与交互
### 4.1 前端显示类
<?php
namespace FlexiblePricing;
/**
- 前端显示处理
*/
class FrontendDisplay {
public function __construct() {
add_action('woocommerce_before_add_to_cart_button', [$this, 'display_price_calculator']);
add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_scripts']);
add_action('wp_ajax_calculate_dynamic_price', [$this, 'ajax_calculate_dynamic_price']);
add_action('wp_ajax_nopriv_calculate_dynamic_price', [$this, 'ajax_calculate_dynamic_price']);
add_filter('woocommerce_get_price_html', [$this, 'display_dynamic_price_range'], 10, 2);
}
/**
* 显示价格计算器
*/
public function display_price_calculator() {
global $product;
if (!$product || !$product->is_type('simple')) {
return;
}
// 获取产品的基础价格
$base_price = $product->get_price();
$product_id = $product->get_id();
// 获取可用的定价规则
$rules = $this->get_available_rules_for_display($product_id);
if (empty($rules)) {
return;
}
// 加载模板
include FLEXIBLE_PRICING_PLUGIN_DIR . 'templates/price-display.php';
}
/**
* 获取用于显示的规则
*/
private function get_available_rules_for_display($product_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'flexible_pricing_rules';
$rules = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name
WHERE (product_id = %d OR product_id = 0)
AND is_active = 1
AND rule_type IN ('quantity', 'user_role')
ORDER BY priority DESC",
$product_id
),
ARRAY_A
);
return $rules;
}
/**
* 显示动态价格范围
*/
public function display_dynamic_price_range($price_html, $product) {
if (is_admin() || !$product->is_type('simple')) {
return $price_html;
}
$product_id = $product->get_id();
$base_price = $product->get_price();
// 获取可能的最低价格
$min_price = $this->calculate_minimum_possible_price($product_id, $base_price);
if ($min_price < $base_price) {
$price_html = sprintf(
'<span class="price"><del>%s</del> <ins>%s起</ins></span>',
wc_price($base_price),
wc_price($min_price)
);
}
return $price_html;
}
/**
* 计算最低可能价格
*/
private function calculate_minimum_possible_price($product_id, $base_price) {
global $wpdb;
$table_name = $wpdb->prefix . 'flexible_pricing_rules';
// 获取所有降价规则
$rules = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name
WHERE (product_id = %d OR product_id = 0)
AND is_active = 1
AND adjustment_type IN ('percentage_decrease', 'fixed_decrease', 'fixed_price')
ORDER BY priority DESC",
$product_id
)
);
$min_price = $base_price;
foreach ($rules as $rule) {
$price_calculator = new PriceCalculator();
$adjusted_price = $price_calculator->apply_price_adjustment($min_price, (array)$rule);
$min_price = min($min_price, $adjusted_price);
}
return $min_price;
}
/**
* AJAX计算动态价格
*/
public function ajax_calculate_dynamic_price() {
check_ajax_referer('flexible_pricing_nonce', 'nonce');
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity']);
$user_id = get_current_user_id();
// 获取产品
$product = wc_get_product($product_id);
if (!$product) {
wp_send_json_error(['message' => __('产品不存在', 'flexible-pricing')]);
}
// 模拟购物车数量
if ($quantity > 0) {
WC()->cart = new WC_Cart();
WC()->cart->add_to_cart($product_id, $quantity);
}
// 计算价格
$price_calculator = new PriceCalculator();
$final_price = $price_calculator->calculate_flexible_price(
$product->get_price(),
$product
);
// 清理模拟的购物车
if ($quantity > 0) {
WC()->cart->empty_cart();
}
wp_send_json_success([
'price' => $final_price,
'price_display' => wc_price($final_price),
'savings' => $product->get_price() - $final_price,
'savings_display' => wc_price($product->get_price() - $final_price)
]);
}
/**
* 加载前端脚本
*/
public function enqueue_frontend_scripts() {
if (!is_product()) {
return;
}
wp_enqueue_script(
'flexible-pricing-frontend',
FLEXIBLE_PRICING_PLUGIN_URL . 'assets/js/frontend-script.js',
['jquery'],
FLEXIBLE_PRICING_VERSION,
true
);
wp_localize_script('flexible-pricing-frontend', 'flexiblePricing', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('flexible_pricing_nonce'),
'i18n' => [
'calculating' => __('计算中...', 'flexible-pricing'),
'quantity' => __('数量', 'flexible-pricing'),
'final_price' => __('最终价格', 'flexible-pricing'),
'you_save' => __('您节省了', 'flexible-pricing')
]
]);
wp_enqueue_style(
'flexible-pricing-frontend',
FLEXIBLE_PRICING_PLUGIN_URL . 'assets/css/frontend-style.css',
[],
FLEXIBLE_PRICING_VERSION
);
}
}
### 4.2 前端价格显示模板
<?php
/**
- 价格显示模板文件
- 路径: templates/price-display.php
*/
?>
<div class="flexible-pricing-calculator" data-product-id="<?php echo esc_attr($product_id); ?>">
<h3><?php _e('价格计算器', 'flexible-pricing'); ?></h3>
<div class="pricing-options">
<?php if (is_user_logged_in()): ?>
<?php
$user = wp_get_current_user();
$user_roles = $user->roles;
?>
<div class="user-role-info">
<p><?php printf(__('当前用户角色: %s', 'flexible-pricing'), implode(', ', $user_roles)); ?></p>
</div>
<?php endif; ?>
<div class="quantity-selector">
<label for="quantity"><?php _e('购买数量:', 'flexible-pricing'); ?></label>
<input type="number"
id="flexible-pricing-quantity"
name="quantity"
value="1"
min="1"
max="99"
class="input-text qty text">
<button type="button" class="button calculate-price">
<?php _e('计算价格', 'flexible-pricing'); ?>
</button>
</div>
<?php if (!empty($rules)): ?>
<div class="pricing-rules-info">
<h4><?php _e('可用定价规则:', 'flexible-pricing'); ?></h4>
<ul>
<?php
$price_calculator = new FlexiblePricingPriceCalculator();
foreach ($rules as $rule):
if ($price_calculator->check_rule_condition($rule, $product)):
?>
<li>
<?php
$condition = json_decode($rule['rule_condition'], true);
switch ($rule['rule_type']) {
case 'quantity':
printf(__('购买 %d 件以上可享受优惠', 'flexible-pricing'),
$condition['min_quantity'] ?? 0);
break;
case 'user_role':
printf(__('%s 会员专享价', 'flexible-pricing'),
$condition['user_role'] ?? '');
break;
}
?>
</li>
<?php
endif;
endforeach;
?>
</ul>
</div>
<?php endif; ?>
<div class="price-result" style="display: none;">
<div class="final-price">
<strong><?php _e('最终价格:', 'flexible-pricing'); ?></strong>
<span class="price-amount"></span>
</div>
<div class="price-savings">
<strong><?php _e('节省金额:', 'flexible-pricing'); ?></strong>
<span class="savings-amount"></span>
</div>
</div>
</div>
</div>
## 高级功能扩展
### 5.1 批量定价规则导入
<?php
/**
- 批量定价规则导入类
- 扩展功能:支持从CSV文件导入定价规则
*/
namespace FlexiblePricingExtensions;
class BulkImport {
public function __construct() {
add_action('admin_menu', [$this, 'add_import_page']);
add_action('admin_post_import_pricing_rules', [$this, 'handle_import']);
}
/**
* 添加导入页面
*/
public function add_import_page() {
add_submenu_page(
'woocommerce',
__('批量导入定价规则', 'flexible-pricing'),
__('批量导入', 'flexible-pricing'),
'manage_options',
'flexible-pricing-import',
[$this, 'render_import_page']
);
}
/**
* 渲染导入页面
*/
public function render_import_page() {
?>
<div class="wrap">
<h1><?php _e('批量导入定价规则', 'flexible-pricing'); ?></h1>
<div class="card">
<h2><?php _e('导入说明', 'flexible-pricing'); ?></h2>
<p><?php _e('请上传CSV文件,文件格式如下:', 'flexible-pricing'); ?></p>
<table class="widefat">
<thead>
<tr>
<th>product_id</th>
<th>rule_type</th>
<th>rule_condition</th>
<th>adjustment_type</th>
<th>adjustment_value</th>
<th>priority</th>
</tr>
</thead>
