文章目录[隐藏]
WordPress文创插件开发:柔性版税分成模块技术教程
一、项目概述与需求分析
在文创产品交易平台中,版税分成是一个核心功能。传统的固定比例分成模式已无法满足复杂多变的合作需求。本文将详细介绍如何在WordPress插件中开发一个柔性版税分成模块,支持动态比例调整、多级分成和实时结算功能。
需求分析
- 支持多个受益人按不同比例分成
- 允许设置分成触发条件(如销售额阈值)
- 实时计算和显示分成明细
- 提供分成记录和结算历史
- 与现有支付系统无缝集成
二、数据库设计与数据模型
首先,我们需要设计合理的数据库结构来存储版税分成相关数据。
<?php
/**
* 版税分成数据库表结构
*/
global $wpdb;
// 定义表名
$royalty_table = $wpdb->prefix . 'cultural_royalty_splits';
$royalty_logs_table = $wpdb->prefix . 'cultural_royalty_logs';
// 创建版税分成表SQL
$royalty_table_sql = "
CREATE TABLE IF NOT EXISTS {$royalty_table} (
id INT(11) NOT NULL AUTO_INCREMENT,
product_id INT(11) NOT NULL COMMENT '产品ID',
beneficiary_id INT(11) NOT NULL COMMENT '受益人用户ID',
beneficiary_type VARCHAR(50) DEFAULT 'user' COMMENT '受益人类型(user/company)',
percentage DECIMAL(5,2) NOT NULL COMMENT '分成百分比',
minimum_amount DECIMAL(10,2) DEFAULT 0 COMMENT '最低分成金额',
priority INT(11) DEFAULT 0 COMMENT '分成优先级',
conditions TEXT COMMENT '分成条件(JSON格式)',
is_active TINYINT(1) DEFAULT 1 COMMENT '是否激活',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
INDEX idx_product (product_id),
INDEX idx_beneficiary (beneficiary_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
";
// 创建分成记录表SQL
$royalty_logs_sql = "
CREATE TABLE IF NOT EXISTS {$royalty_logs_table} (
id INT(11) NOT NULL AUTO_INCREMENT,
order_id INT(11) NOT NULL COMMENT '订单ID',
product_id INT(11) NOT NULL COMMENT '产品ID',
beneficiary_id INT(11) NOT NULL COMMENT '受益人ID',
amount DECIMAL(10,2) NOT NULL COMMENT '分成金额',
percentage DECIMAL(5,2) NOT NULL COMMENT '实际分成比例',
base_amount DECIMAL(10,2) NOT NULL COMMENT '计算基数金额',
status ENUM('pending', 'processed', 'paid', 'cancelled') DEFAULT 'pending',
calculated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
paid_at DATETIME NULL,
metadata TEXT COMMENT '额外数据(JSON格式)',
PRIMARY KEY (id),
INDEX idx_order (order_id),
INDEX idx_beneficiary_status (beneficiary_id, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
";
// 执行创建表
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($royalty_table_sql);
dbDelta($royalty_logs_sql);
?>
三、核心类设计与实现
接下来,我们创建版税分成管理的核心类。
<?php
/**
* 柔性版税分成管理类
*/
class FlexibleRoyaltyManager {
private $db;
private $royalty_table;
private $royalty_logs_table;
public function __construct() {
global $wpdb;
$this->db = $wpdb;
$this->royalty_table = $wpdb->prefix . 'cultural_royalty_splits';
$this->royalty_logs_table = $wpdb->prefix . 'cultural_royalty_logs';
}
/**
* 添加版税分成规则
* @param array $data 分成规则数据
* @return int|false 插入ID或false
*/
public function add_royalty_rule($data) {
$defaults = array(
'product_id' => 0,
'beneficiary_id' => 0,
'beneficiary_type' => 'user',
'percentage' => 0.00,
'minimum_amount' => 0.00,
'priority' => 0,
'conditions' => '{}',
'is_active' => 1
);
$data = wp_parse_args($data, $defaults);
// 验证百分比总和不超过100%
if (!$this->validate_percentage_total($data['product_id'], $data['percentage'])) {
return new WP_Error('invalid_percentage', '分成比例总和不能超过100%');
}
$result = $this->db->insert(
$this->royalty_table,
$data,
array('%d', '%d', '%s', '%f', '%f', '%d', '%s', '%d')
);
return $result ? $this->db->insert_id : false;
}
/**
* 验证分成比例总和
* @param int $product_id 产品ID
* @param float $new_percentage 新比例
* @return bool 是否有效
*/
private function validate_percentage_total($product_id, $new_percentage) {
$query = $this->db->prepare(
"SELECT SUM(percentage) as total FROM {$this->royalty_table}
WHERE product_id = %d AND is_active = 1",
$product_id
);
$result = $this->db->get_var($query);
$current_total = floatval($result);
return ($current_total + $new_percentage) <= 100.00;
}
/**
* 计算订单分成
* @param int $order_id 订单ID
* @param int $product_id 产品ID
* @param float $amount 订单金额
* @return array 分成结果
*/
public function calculate_royalties($order_id, $product_id, $amount) {
// 获取有效的分成规则
$rules = $this->get_active_rules($product_id);
if (empty($rules)) {
return array();
}
$royalties = array();
$remaining_amount = $amount;
$remaining_percentage = 100.00;
// 按优先级排序
usort($rules, function($a, $b) {
return $a->priority - $b->priority;
});
foreach ($rules as $rule) {
// 检查分成条件
if (!$this->check_conditions($rule->conditions, $amount)) {
continue;
}
$rule_amount = 0;
// 计算分成金额
if ($rule->percentage > 0) {
$rule_amount = $amount * ($rule->percentage / 100);
// 检查最低金额要求
if ($rule->minimum_amount > 0 && $rule_amount < $rule->minimum_amount) {
$rule_amount = $rule->minimum_amount;
}
// 确保不超过剩余金额
if ($rule_amount > $remaining_amount) {
$rule_amount = $remaining_amount;
}
}
if ($rule_amount > 0) {
$royalty_data = array(
'order_id' => $order_id,
'product_id' => $product_id,
'beneficiary_id' => $rule->beneficiary_id,
'amount' => round($rule_amount, 2),
'percentage' => $rule->percentage,
'base_amount' => $amount,
'status' => 'pending',
'metadata' => json_encode(array(
'beneficiary_type' => $rule->beneficiary_type,
'rule_id' => $rule->id,
'calculated_at' => current_time('mysql')
))
);
// 保存分成记录
$this->db->insert(
$this->royalty_logs_table,
$royalty_data,
array('%d', '%d', '%d', '%f', '%f', '%f', '%s', '%s')
);
$royalties[] = $royalty_data;
$remaining_amount -= $rule_amount;
if ($remaining_amount <= 0) {
break;
}
}
}
return $royalties;
}
/**
* 获取产品的有效分成规则
* @param int $product_id 产品ID
* @return array 分成规则列表
*/
private function get_active_rules($product_id) {
$query = $this->db->prepare(
"SELECT * FROM {$this->royalty_table}
WHERE product_id = %d AND is_active = 1
ORDER BY priority ASC",
$product_id
);
return $this->db->get_results($query);
}
/**
* 检查分成条件
* @param string $conditions_json JSON格式的条件
* @param float $amount 订单金额
* @return bool 是否满足条件
*/
private function check_conditions($conditions_json, $amount) {
$conditions = json_decode($conditions_json, true);
if (empty($conditions)) {
return true;
}
// 检查金额阈值条件
if (isset($conditions['min_amount']) && $amount < $conditions['min_amount']) {
return false;
}
if (isset($conditions['max_amount']) && $amount > $conditions['max_amount']) {
return false;
}
// 可以扩展其他条件检查
// 如:特定用户、特定时间段、促销活动等
return true;
}
/**
* 获取用户的分成统计
* @param int $user_id 用户ID
* @param string $time_range 时间范围
* @return array 统计信息
*/
public function get_user_royalty_stats($user_id, $time_range = 'month') {
$date_condition = '';
switch ($time_range) {
case 'today':
$date_condition = "AND DATE(calculated_at) = CURDATE()";
break;
case 'week':
$date_condition = "AND calculated_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
break;
case 'month':
$date_condition = "AND calculated_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
break;
case 'year':
$date_condition = "AND calculated_at >= DATE_SUB(NOW(), INTERVAL 365 DAY)";
break;
}
$query = $this->db->prepare(
"SELECT
COUNT(*) as total_royalties,
SUM(amount) as total_amount,
AVG(percentage) as avg_percentage,
status,
COUNT(CASE WHEN status = 'paid' THEN 1 END) as paid_count,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) as paid_amount
FROM {$this->royalty_logs_table}
WHERE beneficiary_id = %d
{$date_condition}
GROUP BY status",
$user_id
);
return $this->db->get_results($query);
}
}
?>
四、管理界面与用户面板
4.1 管理后台界面
<?php
/**
* 版税分成管理后台界面
*/
class RoyaltyAdminInterface {
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_submenu_page(
'cultural-products',
'版税分成管理',
'版税分成',
'manage_options',
'cultural-royalties',
array($this, 'render_admin_page')
);
}
/**
* 渲染管理页面
*/
public function render_admin_page() {
$royalty_manager = new FlexibleRoyaltyManager();
// 处理表单提交
if (isset($_POST['add_royalty_rule'])) {
$this->handle_add_rule($royalty_manager);
}
// 获取所有分成规则
$rules = $this->get_all_rules();
?>
<div class="wrap">
<h1>柔性版税分成管理</h1>
<div class="royalty-admin-container">
<!-- 添加新规则表单 -->
<div class="card">
<h2>添加分成规则</h2>
<form method="post" action="">
<?php wp_nonce_field('add_royalty_rule', 'royalty_nonce'); ?>
<table class="form-table">
<tr>
<th><label for="product_id">产品ID</label></th>
<td>
<input type="number" id="product_id" name="product_id" required min="1">
<p class="description">关联的产品ID</p>
</td>
</tr>
<tr>
<th><label for="beneficiary_id">受益人ID</label></th>
<td>
<input type="number" id="beneficiary_id" name="beneficiary_id" required min="1">
<p class="description">受益用户ID</p>
</td>
</tr>
<tr>
<th><label for="percentage">分成比例 (%)</label></th>
<td>
<input type="number" id="percentage" name="percentage"
step="0.01" min="0" max="100" required>
<p class="description">0-100之间的百分比</p>
</td>
</tr>
<tr>
<th><label for="conditions">分成条件</label></th>
<td>
<textarea id="conditions" name="conditions" rows="3"
placeholder='{"min_amount": 100, "max_amount": 10000}'></textarea>
<p class="description">JSON格式的分成条件</p>
</td>
</tr>
</table>
<input type="submit" name="add_royalty_rule"
class="button button-primary" value="添加规则">
</form>
</div>
<!-- 现有规则列表 -->
<div class="card">
<h2>现有分成规则</h2>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>ID</th>
<th>产品ID</th>
<th>受益人ID</th>
<th>比例</th>
<th>优先级</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($rules as $rule): ?>
<tr>
<td><?php echo $rule->id; ?></td>
<td><?php echo $rule->product_id; ?></td>
<td><?php echo $rule->beneficiary_id; ?></td>
<td><?php echo $rule->percentage; ?>%</td>
<td><?php echo $rule->priority; ?></td>
<td>
<span class="status-<?php echo $rule->is_active ? 'active' : 'inactive'; ?>">
<?php echo $rule->is_active ? '激活' : '未激活'; ?>
</span>
</td>
<td>
<button class="button button-small edit-rule"
data-id="<?php echo $rule->id; ?>">编辑</button>
<button class="button button-small delete-rule"
data-id="<?php echo $rule->id; ?>">删除</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
<style>
.royalty-admin-container {
display: grid;
gap: 20px;
margin-top: 20px;
}
.card {
background: #fff;
padding: 20px;
border: 1px solid #ccd0d4;
box-shadow: 0 1px 1px rgba(0,0,0,.04);
}
.status-active {
color: #46b450;
font-weight: bold;
}
.status-inactive {
color: #dc3232;
}
</style>
<script>
jQuery(document).ready(function($) {
// 编辑规则
$('.edit-rule').on('click', function() {
var ruleId = $(this).data('id');
// 这里可以添加AJAX加载编辑表单的逻辑
alert('编辑规则 #' + ruleId);
});
// 删除规则
$('.delete-rule').on('click', function() {
if (confirm('确定要删除这个分成规则吗?')) {
var ruleId = $(this).data('id');
// 这里可以添加AJAX删除逻辑
alert('删除规则 #' + ruleId);
}
});
});
</script>
<?php
}
/**
* 获取所有分成规则
*/
private function get_all_rules() {
global $wpdb;
$table = $wpdb->prefix . 'cultural_royalty_splits';
return $wpdb->get_results(
"SELECT * FROM {$table} ORDER BY product_id, priority ASC"
);
}
/**
* 处理添加规则表单
*/
private function handle_add_rule($royalty_manager) {
if (!wp_verify_nonce($_POST['royalty_nonce'], 'add_royalty_rule')) {
wp_die('安全验证失败');
}
$data = array(
id']),
'beneficiary_id' => intval($_POST['beneficiary_id']),
'percentage' => floatval($_POST['percentage']),
'conditions' => sanitize_textarea_field($_POST['conditions'])
);
$result = $royalty_manager->add_royalty_rule($data);
if (is_wp_error($result)) {
echo '<div class="notice notice-error"><p>' . $result->get_error_message() . '</p></div>';
} elseif ($result) {
echo '<div class="notice notice-success"><p>规则添加成功!</p></div>';
}
}
/**
* 加载管理脚本
*/
public function enqueue_admin_scripts($hook) {
if ($hook !== 'cultural-products_page_cultural-royalties') {
return;
}
wp_enqueue_script('royalty-admin', plugins_url('js/royalty-admin.js', __FILE__), array('jquery'), '1.0.0', true);
wp_enqueue_style('royalty-admin', plugins_url('css/royalty-admin.css', __FILE__));
}
}
?>
### 4.2 用户前端面板
<?php
/**
- 用户版税分成前端面板
*/
class UserRoyaltyDashboard {
public function __construct() {
add_shortcode('user_royalty_dashboard', array($this, 'render_dashboard'));
add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
}
/**
* 渲染用户仪表板
*/
public function render_dashboard() {
if (!is_user_logged_in()) {
return '<p>请先登录查看您的分成信息。</p>';
}
$user_id = get_current_user_id();
$royalty_manager = new FlexibleRoyaltyManager();
// 获取用户统计
$stats = $royalty_manager->get_user_royalty_stats($user_id, 'month');
// 获取最近分成记录
$recent_royalties = $this->get_user_recent_royalties($user_id);
ob_start();
?>
<div class="user-royalty-dashboard">
<h2>我的版税分成</h2>
<!-- 统计卡片 -->
<div class="royalty-stats-grid">
<div class="stat-card total-earnings">
<h3>本月预计收入</h3>
<div class="stat-value">
<?php echo $this->calculate_total_earnings($stats); ?>元
</div>
</div>
<div class="stat-card pending-royalties">
<h3>待处理分成</h3>
<div class="stat-value">
<?php echo $this->count_pending_royalties($stats); ?>笔
</div>
</div>
<div class="stat-card paid-royalties">
<h3>已支付分成</h3>
<div class="stat-value">
<?php echo $this->calculate_paid_amount($stats); ?>元
</div>
</div>
</div>
<!-- 分成记录表格 -->
<div class="royalty-records">
<h3>最近分成记录</h3>
<table class="royalty-table">
<thead>
<tr>
<th>日期</th>
<th>产品</th>
<th>订单号</th>
<th>分成金额</th>
<th>比例</th>
<th>状态</th>
</tr>
</thead>
<tbody>
<?php foreach ($recent_royalties as $royalty): ?>
<tr>
<td><?php echo date('Y-m-d', strtotime($royalty->calculated_at)); ?></td>
<td>
<a href="<?php echo get_permalink($royalty->product_id); ?>">
<?php echo get_the_title($royalty->product_id); ?>
</a>
</td>
<td>#<?php echo $royalty->order_id; ?></td>
<td class="amount"><?php echo $royalty->amount; ?>元</td>
<td><?php echo $royalty->percentage; ?>%</td>
<td class="status-<?php echo $royalty->status; ?>">
<?php echo $this->get_status_label($royalty->status); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php if (empty($recent_royalties)): ?>
<p class="no-records">暂无分成记录</p>
<?php endif; ?>
</div>
<!-- 分成趋势图表 -->
<div class="royalty-chart-container">
<h3>分成趋势</h3>
<canvas id="royaltyTrendChart" width="400" height="200"></canvas>
</div>
</div>
<style>
.user-royalty-dashboard {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.royalty-stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin: 30px 0;
}
.stat-card {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
text-align: center;
}
.stat-card h3 {
margin: 0 0 10px 0;
color: #666;
font-size: 14px;
text-transform: uppercase;
}
.stat-value {
font-size: 28px;
font-weight: bold;
color: #333;
}
.total-earnings .stat-value {
color: #4CAF50;
}
.royalty-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background: white;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.royalty-table th,
.royalty-table td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #eee;
}
.royalty-table th {
background-color: #f8f9fa;
font-weight: 600;
}
.status-pending {
color: #ff9800;
font-weight: bold;
}
.status-paid {
color: #4CAF50;
font-weight: bold;
}
.status-cancelled {
color: #f44336;
font-weight: bold;
}
.amount {
font-weight: bold;
color: #2196F3;
}
.no-records {
text-align: center;
padding: 40px;
color: #999;
font-style: italic;
}
.royalty-chart-container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-top: 30px;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
// 初始化图表
var ctx = document.getElementById('royaltyTrendChart').getContext('2d');
// 这里应该通过AJAX获取实际数据
var chartData = {
labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
datasets: [{
label: '分成收入',
data: [1200, 1900, 1500, 2500, 2200, 3000],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 2,
tension: 0.4
}]
};
var royaltyChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
tooltip: {
callbacks: {
label: function(context) {
return '收入: ' + context.parsed.y + '元';
}
}
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return value + '元';
}
}
}
}
}
});
});
</script>
<?php
return ob_get_clean();
}
/**
* 获取用户最近分成记录
*/
private function get_user_recent_royalties($user_id, $limit = 10) {
global $wpdb;
$table = $wpdb->prefix . 'cultural_royalty_logs';
return $wpdb->get_results($wpdb->prepare(
"SELECT * FROM {$table}
WHERE beneficiary_id = %d
ORDER BY calculated_at DESC
LIMIT %d",
$user_id, $limit
));
}
/**
* 计算总收入
*/
private function calculate_total_earnings($stats) {
$total = 0;
foreach ($stats as $stat) {
$total += floatval($stat->total_amount);
}
return number_format($total, 2);
}
/**
* 计算待处理分成数量
*/
private function count_pending_royalties($stats) {
$count = 0;
foreach ($stats as $stat) {
if ($stat->status === 'pending') {
$count += intval($stat->total_royalties);
}
}
return $count;
}
/**
* 计算已支付金额
*/
private function calculate_paid_amount($stats) {
$total = 0;
foreach ($stats as $stat) {
if ($stat->status === 'paid') {
$total += floatval($stat->paid_amount);
}
}
return number_format($total, 2);
}
/**
* 获取状态标签
*/
private function get_status_label($status) {
$labels = array(
'pending' => '待处理',
'processed' => '已处理',
'paid' => '已支付',
'cancelled' => '已取消'
);
return isset($labels[$status]) ? $labels[$status] : $status;
}
/**
* 加载前端脚本
*/
public function enqueue_frontend_scripts() {
if (has_shortcode(get_post()->post_content, 'user_royalty_dashboard')) {
wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', array(), '3.7.0');
wp_enqueue_style('royalty-frontend', plugins_url('css/royalty-frontend.css', __FILE__));
}
}
}
?>
## 五、与WooCommerce集成
<?php
/**
- WooCommerce集成类
*/
class WooCommerceRoyaltyIntegration {
public function __construct() {
// 在订单完成时触发分成计算
add_action('woocommerce_order_status_completed', array($this, 'process_order_royalties'), 10, 2);
// 在订单详情页显示分成信息
add_action('woocommerce_order_details_after_order_table', array($this, 'display_order_royalties'));
// 在产品编辑页添加分成设置
add_action('woocommerce_product_options_general_product_data', array($this, 'add_product_royalty_fields'));
add_action('woocommerce_process_product_meta', array($this, 'save_product_royalty_fields'));
}
/**
* 处理订单分成
*/
public function process_order_royalties($order_id, $order) {
$royalty_manager = new FlexibleRoyaltyManager();
foreach ($order->get_items() as $item) {
$product_id = $item->get_product_id();
$quantity = $item->get_quantity();
$line_total = $item->get_total();
// 计算分成
$royalties = $royalty_manager->calculate_royalties(
$order_id,
$product_id,
$line_total
);
// 记录分成处理日志
if (!empty($royalties)) {
$this->log_royalty_processing($order_id, $product_id, $royalties);
}
}
}
/**
* 在订单详情页显示分成信息
*/
public function display_order_royalties($order) {
$order_id = $order->get_id();
$royalties = $this->get_order_royalties($order_id);
if (empty($royalties)) {
return;
}
?>
<section class="order-royalty-details">
<h2>版税分成详情</h2>
<table class="woocommerce-table shop_table royalty_details">
<thead>
<tr>
<th>受益人</th>
<th>产品</th>
<th>分成比例</th>
<th>分成金额</th>
<th>状态</th>
</tr>
</thead>
<tbody>
<?php foreach ($royalties as $royalty): ?>
<tr>
<td>
<?php
$user = get_user_by('id', $royalty->beneficiary_id);
echo $user ? $user->display_name : '用户#' . $royalty->beneficiary_id;
?>
</td>
<td><?php echo get_the_title($royalty->product_id); ?></td>
<td><?php echo $royalty->percentage; ?>%</td>
<td><?php echo wc_price($royalty->amount); ?></td>
<td>
<span class="royalty-status status-<?php echo $royalty->status; ?>">
<?php echo $this->get_royalty_status_label($royalty->status); ?>
</span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<td colspan="3"><strong>总分成金额</strong></td>
<td colspan="2">
<strong><?php
$total = array_sum(array_column($royalties, 'amount'));
echo wc_price($total);
?></strong>
</td>
</tr>
</tfoot>
</table>
</section>
<style>
.order-royalty-details {
margin: 40px 0;
padding: 20px;
background: #f8f8f8;
border-radius: 5px;
}
.royalty_details th,
.royalty_details td {
padding: 12px;
border-bottom: 1px solid #ddd;
}
.royalty-status {
padding: 4px 8px;
border-radius: 3px;
font-size: 12px;
font-weight: bold;
}
.status-pending {
background: #fff3cd;
color: #856404;
}
.status-paid {
background: #d4edda;
color: #155724;
}
</style>
<?php
}
/**
* 在产品编辑页添加分成设置字段
*/
public function add_product_royalty_fields() {
global $product_object;
echo '<div class="options_group">';
woocommerce_wp_checkbox(array(
'id' => '_enable_royalty_splits',
'label' => '启用版税分成',
'description' => '启用此产品的版税分成功能'
));
echo '</div>';
// 显示现有分成规则
$this->display_product_royalty_rules($product_object->get_id());
}
/**
* 显示产品分成规则
*/
private function display_product_royalty_rules($product_id) {
$royalty_manager = new FlexibleRoyaltyManager();
$rules = $royalty_manager->get_active_rules($product_id);
if (empty($rules)) {
return;
}
?>
<div class="options_group">
<h4>当前分成规则</h4>
<table class="widefat">
<thead>
<tr>
<th>受益人</th>
<th>比例</th>
<th>优先级</th>
<th>状态</th>
</tr>
</thead>
<tbody>
<?php foreach ($rules as $rule): ?>
<tr>
<td>
<?php
$user = get_user_by('id', $rule->beneficiary_id);
echo $user ? $user->display_name : '用户#' . $rule->beneficiary_id;
?>
</td>
<td><?php echo $rule->percentage; ?>%</td>
<td><?php echo $rule->priority; ?></td>
<td><?php echo $rule->is_active ? '激活' : '未激活'; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
/**
* 保存产品分成设置
*/
public function save_product_royalty_fields($product_id) {
$enable_royalty = isset($_POST['_enable_royalty_splits']) ? 'yes' : 'no';
update_post_meta($product_id, '_enable_royalty_splits', $
