文章目录[隐藏]
WordPress开发教程:集成网站用户积分兑换虚拟礼物与打赏系统
引言:为什么WordPress网站需要用户互动系统
在当今互联网环境中,用户参与度已成为衡量网站成功与否的关键指标。无论是内容型网站、社区论坛还是电商平台,如何增强用户粘性、促进用户互动都是运营者面临的重要课题。用户积分系统和虚拟礼物打赏功能正是解决这一问题的有效工具。
WordPress作为全球最流行的内容管理系统,其强大的扩展性和灵活性使其成为实现这些功能的理想平台。通过代码二次开发,我们可以在WordPress网站上集成完整的用户积分、虚拟礼物兑换和打赏系统,从而提升用户体验,增加网站活跃度,甚至创造新的盈利模式。
本教程将详细讲解如何通过WordPress代码二次开发,实现一个完整的用户积分兑换虚拟礼物与打赏系统,涵盖从数据库设计、功能实现到前端展示的全过程。
系统架构设计与技术选型
1.1 系统功能模块划分
在开始开发之前,我们需要明确系统的功能模块:
- 用户积分管理模块:包括积分获取、消费、查询和统计功能
- 虚拟礼物商城模块:礼物的展示、分类、购买和赠送功能
- 打赏系统模块:支持内容打赏、用户间打赏和打赏记录查询
- 后台管理模块:积分规则设置、礼物管理、数据统计等功能
- 前端交互模块:用户界面、AJAX交互和实时通知
1.2 技术栈选择
- 核心框架:WordPress 5.0+
- 数据库:MySQL 5.6+
- 前端技术:HTML5, CSS3, JavaScript (jQuery/AJAX)
- 安全机制:WordPress Nonce验证、数据过滤与转义
- 缓存优化:Transients API、对象缓存
1.3 数据库表设计
我们需要创建以下自定义数据库表来支持系统功能:
-- 用户积分表
CREATE TABLE wp_user_points (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT(20) NOT NULL,
points INT DEFAULT 0,
total_earned INT DEFAULT 0,
total_spent INT DEFAULT 0,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES wp_users(ID) ON DELETE CASCADE
);
-- 积分记录表
CREATE TABLE wp_points_log (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT(20) NOT NULL,
points_change INT NOT NULL,
action_type VARCHAR(50) NOT NULL,
related_id BIGINT(20),
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES wp_users(ID) ON DELETE CASCADE
);
-- 虚拟礼物表
CREATE TABLE wp_virtual_gifts (
id INT AUTO_INCREMENT PRIMARY KEY,
gift_name VARCHAR(100) NOT NULL,
gift_description TEXT,
gift_price INT NOT NULL,
gift_image VARCHAR(255),
gift_category VARCHAR(50),
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 礼物交易记录表
CREATE TABLE wp_gift_transactions (
id INT AUTO_INCREMENT PRIMARY KEY,
sender_id BIGINT(20) NOT NULL,
receiver_id BIGINT(20) NOT NULL,
gift_id INT NOT NULL,
quantity INT DEFAULT 1,
message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (sender_id) REFERENCES wp_users(ID) ON DELETE CASCADE,
FOREIGN KEY (receiver_id) REFERENCES wp_users(ID) ON DELETE CASCADE,
FOREIGN KEY (gift_id) REFERENCES wp_virtual_gifts(id) ON DELETE CASCADE
);
-- 打赏记录表
CREATE TABLE wp_tip_records (
id INT AUTO_INCREMENT PRIMARY KEY,
tipper_id BIGINT(20) NOT NULL,
receiver_id BIGINT(20) NOT NULL,
post_id BIGINT(20),
points_amount INT NOT NULL,
message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (tipper_id) REFERENCES wp_users(ID) ON DELETE CASCADE,
FOREIGN KEY (receiver_id) REFERENCES wp_users(ID) ON DELETE CASCADE,
FOREIGN KEY (post_id) REFERENCES wp_posts(ID) ON DELETE SET NULL
);
用户积分系统的实现
2.1 积分系统核心类设计
首先,我们创建一个积分系统的核心类,用于处理所有积分相关操作:
<?php
/**
* WordPress用户积分系统核心类
*/
class WP_Points_System {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
// 初始化操作
$this->init_hooks();
}
private function init_hooks() {
// 用户注册时初始化积分账户
add_action('user_register', array($this, 'init_user_points_account'));
// 删除用户时清理积分数据
add_action('delete_user', array($this, 'delete_user_points_data'));
// 添加积分获取规则
add_action('publish_post', array($this, 'award_points_for_publishing'));
add_action('wp_insert_comment', array($this, 'award_points_for_comment'));
add_action('daily_points_check', array($this, 'award_daily_login_points'));
}
/**
* 初始化用户积分账户
*/
public function init_user_points_account($user_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'user_points';
// 检查是否已存在记录
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $table_name WHERE user_id = %d",
$user_id
));
if (!$existing) {
// 新用户赠送初始积分
$initial_points = get_option('points_initial', 100);
$wpdb->insert(
$table_name,
array(
'user_id' => $user_id,
'points' => $initial_points,
'total_earned' => $initial_points
),
array('%d', '%d', '%d')
);
// 记录积分日志
$this->add_points_log(
$user_id,
$initial_points,
'registration',
null,
'新用户注册赠送积分'
);
}
}
/**
* 获取用户当前积分
*/
public function get_user_points($user_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'user_points';
$points = $wpdb->get_var($wpdb->prepare(
"SELECT points FROM $table_name WHERE user_id = %d",
$user_id
));
return $points ? intval($points) : 0;
}
/**
* 增加用户积分
*/
public function add_points($user_id, $points, $action_type, $related_id = null, $description = '') {
global $wpdb;
if ($points <= 0) {
return false;
}
$points_table = $wpdb->prefix . 'user_points';
// 更新用户积分总额
$wpdb->query($wpdb->prepare(
"UPDATE $points_table
SET points = points + %d, total_earned = total_earned + %d
WHERE user_id = %d",
$points, $points, $user_id
));
// 记录积分日志
$this->add_points_log($user_id, $points, $action_type, $related_id, $description);
// 触发积分增加动作
do_action('points_added', $user_id, $points, $action_type);
return true;
}
/**
* 扣除用户积分
*/
public function deduct_points($user_id, $points, $action_type, $related_id = null, $description = '') {
global $wpdb;
if ($points <= 0) {
return false;
}
// 检查用户是否有足够积分
$current_points = $this->get_user_points($user_id);
if ($current_points < $points) {
return false;
}
$points_table = $wpdb->prefix . 'user_points';
// 更新用户积分总额
$wpdb->query($wpdb->prepare(
"UPDATE $points_table
SET points = points - %d, total_spent = total_spent + %d
WHERE user_id = %d",
$points, $points, $user_id
));
// 记录积分日志
$this->add_points_log($user_id, -$points, $action_type, $related_id, $description);
// 触发积分扣除动作
do_action('points_deducted', $user_id, $points, $action_type);
return true;
}
/**
* 添加积分记录
*/
private function add_points_log($user_id, $points_change, $action_type, $related_id, $description) {
global $wpdb;
$log_table = $wpdb->prefix . 'points_log';
$wpdb->insert(
$log_table,
array(
'user_id' => $user_id,
'points_change' => $points_change,
'action_type' => $action_type,
'related_id' => $related_id,
'description' => $description
),
array('%d', '%d', '%s', '%d', '%s')
);
return $wpdb->insert_id;
}
/**
* 获取用户积分记录
*/
public function get_user_points_log($user_id, $limit = 20, $offset = 0) {
global $wpdb;
$log_table = $wpdb->prefix . 'points_log';
$logs = $wpdb->get_results($wpdb->prepare(
"SELECT * FROM $log_table
WHERE user_id = %d
ORDER BY created_at DESC
LIMIT %d OFFSET %d",
$user_id, $limit, $offset
));
return $logs;
}
/**
* 发布文章奖励积分
*/
public function award_points_for_publishing($post_id) {
$post = get_post($post_id);
$user_id = $post->post_author;
// 避免重复奖励
if (get_post_meta($post_id, '_points_awarded', true)) {
return;
}
$points_for_post = get_option('points_for_post', 50);
if ($points_for_post > 0) {
$this->add_points(
$user_id,
$points_for_post,
'publish_post',
$post_id,
sprintf('发布文章《%s》', $post->post_title)
);
update_post_meta($post_id, '_points_awarded', true);
}
}
/**
* 评论奖励积分
*/
public function award_points_for_comment($comment_id) {
$comment = get_comment($comment_id);
$user_id = $comment->user_id;
// 只奖励已批准的评论
if ($comment->comment_approved != 1) {
return;
}
// 避免重复奖励
if (get_comment_meta($comment_id, '_points_awarded', true)) {
return;
}
$points_for_comment = get_option('points_for_comment', 10);
if ($points_for_comment > 0 && $user_id > 0) {
$this->add_points(
$user_id,
$points_for_comment,
'add_comment',
$comment_id,
'发表评论'
);
update_comment_meta($comment_id, '_points_awarded', true);
}
}
/**
* 每日登录奖励积分
*/
public function award_daily_login_points() {
// 获取所有活跃用户
$users = get_users(array(
'meta_key' => 'last_login_date',
'meta_value' => date('Y-m-d', strtotime('-1 day')),
'meta_compare' => '>='
));
$points_for_daily_login = get_option('points_for_daily_login', 5);
foreach ($users as $user) {
$this->add_points(
$user->ID,
$points_for_daily_login,
'daily_login',
null,
'每日登录奖励'
);
}
}
/**
* 删除用户积分数据
*/
public function delete_user_points_data($user_id) {
global $wpdb;
$points_table = $wpdb->prefix . 'user_points';
$log_table = $wpdb->prefix . 'points_log';
$wpdb->delete($points_table, array('user_id' => $user_id), array('%d'));
$wpdb->delete($log_table, array('user_id' => $user_id), array('%d'));
}
}
2.2 积分系统短代码与模板标签
为了让前端可以方便地显示积分信息,我们需要创建一些短代码和模板函数:
/**
* 积分系统短代码和模板函数
*/
class WP_Points_Template_Functions {
/**
* 显示当前用户积分的短代码
*/
public static function points_balance_shortcode($atts) {
if (!is_user_logged_in()) {
return '<div class="points-balance">请登录查看积分</div>';
}
$user_id = get_current_user_id();
$points_system = WP_Points_System::get_instance();
$points = $points_system->get_user_points($user_id);
return sprintf(
'<div class="points-balance">当前积分: <strong>%d</strong></div>',
$points
);
}
/**
* 显示用户积分排行榜的短代码
*/
public static function points_leaderboard_shortcode($atts) {
$atts = shortcode_atts(array(
'limit' => 10,
'show_avatar' => true,
'show_points' => true
), $atts);
global $wpdb;
$points_table = $wpdb->prefix . 'user_points';
$users_table = $wpdb->prefix . 'users';
$leaderboard = $wpdb->get_results($wpdb->prepare(
"SELECT u.ID, u.user_login, u.display_name, p.points
FROM $points_table p
INNER JOIN $users_table u ON p.user_id = u.ID
ORDER BY p.points DESC
LIMIT %d",
$atts['limit']
));
if (empty($leaderboard)) {
return '<p>暂无积分数据</p>';
}
$output = '<div class="points-leaderboard"><h3>积分排行榜</h3><ol>';
foreach ($leaderboard as $index => $user) {
$output .= '<li>';
if ($atts['show_avatar']) {
$output .= get_avatar($user->ID, 40) . ' ';
}
$output .= esc_html($user->display_name ?: $user->user_login);
if ($atts['show_points']) {
$output .= sprintf(' <span class="points-count">(%d 积分)</span>', $user->points);
}
$output .= '</li>';
}
$output .= '</ol></div>';
return $output;
}
/**
* 模板函数:获取用户积分
*/
public static function get_user_points($user_id = null) {
if (!$user_id) {
$user_id = get_current_user_id();
}
$points_system = WP_Points_System::get_instance();
return $points_system->get_user_points($user_id);
}
/**
* 模板函数:显示积分日志
*/
public static function display_points_log($user_id = null, $limit = 20) {
if (!$user_id) {
$user_id = get_current_user_id();
}
$points_system = WP_Points_System::get_instance();
$logs = $points_system->get_user_points_log($user_id, $limit);
if (empty($logs)) {
return '<p>暂无积分记录</p>';
}
$output = '<table class="points-log-table"><thead>
<tr><th>时间</th><th>操作</th><th>积分变化</th><th>描述</th></tr>
</thead><tbody>';
foreach ($logs as $log) {
$points_change = $log->points_change > 0 ?
sprintf('+%d', $log->points_change) :
sprintf('%d', $log->points_change);
$points_class = $log->points_change > 0 ? 'points-increase' : 'points-decrease';
$output .= sprintf(
'<tr>
<td>%s</td>
<td>%s</td>
<td class="%s">%s</td>
<td>%s</td>
</tr>',
$log->created_at,
esc_html($log->action_type),
$points_class,
$points_change,
esc_html($log->description)
);
}
$output .= '</tbody></table>';
return $output;
}
}
// 注册短代码
add_shortcode('points_balance', array('WP_Points_Template_Functions', 'points_balance_shortcode'));
add_shortcode('points_leaderboard', array('WP_Points_Template_Functions', 'points_leaderboard_shortcode'));
虚拟礼物系统的实现
3.1 虚拟礼物管理类
<?php
/**
* WordPress虚拟礼物系统
*/
class WP_Virtual_Gifts_System {
private static $instance = null;
get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->init_hooks();
}
private function init_hooks() {
// 初始化礼物数据表
add_action('init', array($this, 'check_gifts_table'));
// 添加AJAX处理
add_action('wp_ajax_purchase_gift', array($this, 'ajax_purchase_gift'));
add_action('wp_ajax_nopriv_purchase_gift', array($this, 'ajax_no_permission'));
add_action('wp_ajax_send_gift', array($this, 'ajax_send_gift'));
add_action('wp_ajax_nopriv_send_gift', array($this, 'ajax_no_permission'));
// 添加管理菜单
add_action('admin_menu', array($this, 'add_admin_menu'));
}
/**
* 检查并创建礼物数据表
*/
public function check_gifts_table() {
global $wpdb;
$gifts_table = $wpdb->prefix . 'virtual_gifts';
$transactions_table = $wpdb->prefix . 'gift_transactions';
// 检查表是否存在,如果不存在则创建
if ($wpdb->get_var("SHOW TABLES LIKE '$gifts_table'") != $gifts_table) {
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $gifts_table (
id INT AUTO_INCREMENT PRIMARY KEY,
gift_name VARCHAR(100) NOT NULL,
gift_description TEXT,
gift_price INT NOT NULL,
gift_image VARCHAR(255),
gift_category VARCHAR(50),
is_active BOOLEAN DEFAULT TRUE,
sort_order INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 插入示例礼物数据
$this->insert_sample_gifts();
}
if ($wpdb->get_var("SHOW TABLES LIKE '$transactions_table'") != $transactions_table) {
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $transactions_table (
id INT AUTO_INCREMENT PRIMARY KEY,
sender_id BIGINT(20) NOT NULL,
receiver_id BIGINT(20) NOT NULL,
gift_id INT NOT NULL,
quantity INT DEFAULT 1,
message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (sender_id) REFERENCES {$wpdb->prefix}users(ID) ON DELETE CASCADE,
FOREIGN KEY (receiver_id) REFERENCES {$wpdb->prefix}users(ID) ON DELETE CASCADE,
FOREIGN KEY (gift_id) REFERENCES $gifts_table(id) ON DELETE CASCADE
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
}
/**
* 插入示例礼物数据
*/
private function insert_sample_gifts() {
global $wpdb;
$gifts_table = $wpdb->prefix . 'virtual_gifts';
$sample_gifts = array(
array(
'gift_name' => '玫瑰花',
'gift_description' => '表达喜爱之情',
'gift_price' => 10,
'gift_category' => '情感',
'sort_order' => 1
),
array(
'gift_name' => '咖啡',
'gift_description' => '请喝一杯咖啡',
'gift_price' => 20,
'gift_category' => '日常',
'sort_order' => 2
),
array(
'gift_name' => '奖杯',
'gift_description' => '表彰优秀贡献',
'gift_price' => 50,
'gift_category' => '荣誉',
'sort_order' => 3
),
array(
'gift_name' => '钻石',
'gift_description' => '珍贵的心意',
'gift_price' => 100,
'gift_category' => '豪华',
'sort_order' => 4
),
array(
'gift_name' => '蛋糕',
'gift_description' => '庆祝特别时刻',
'gift_price' => 30,
'gift_category' => '庆祝',
'sort_order' => 5
)
);
foreach ($sample_gifts as $gift) {
$wpdb->insert($gifts_table, $gift);
}
}
/**
* 获取所有可用礼物
*/
public function get_available_gifts($category = null) {
global $wpdb;
$gifts_table = $wpdb->prefix . 'virtual_gifts';
$where = "WHERE is_active = 1";
if ($category) {
$where .= $wpdb->prepare(" AND gift_category = %s", $category);
}
$gifts = $wpdb->get_results(
"SELECT * FROM $gifts_table
$where
ORDER BY sort_order ASC, gift_price ASC"
);
return $gifts;
}
/**
* 获取单个礼物信息
*/
public function get_gift($gift_id) {
global $wpdb;
$gifts_table = $wpdb->prefix . 'virtual_gifts';
$gift = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $gifts_table WHERE id = %d",
$gift_id
));
return $gift;
}
/**
* 购买礼物
*/
public function purchase_gift($user_id, $gift_id, $quantity = 1) {
$gift = $this->get_gift($gift_id);
if (!$gift || !$gift->is_active) {
return array('success' => false, 'message' => '礼物不存在或已下架');
}
$total_cost = $gift->gift_price * $quantity;
// 检查用户积分是否足够
$points_system = WP_Points_System::get_instance();
$user_points = $points_system->get_user_points($user_id);
if ($user_points < $total_cost) {
return array('success' => false, 'message' => '积分不足');
}
// 扣除积分
$deduct_result = $points_system->deduct_points(
$user_id,
$total_cost,
'purchase_gift',
$gift_id,
sprintf('购买礼物「%s」x%d', $gift->gift_name, $quantity)
);
if (!$deduct_result) {
return array('success' => false, 'message' => '积分扣除失败');
}
// 这里可以添加礼物库存逻辑,如果需要的话
return array(
'success' => true,
'message' => '购买成功',
'gift_id' => $gift_id,
'quantity' => $quantity,
'total_cost' => $total_cost
);
}
/**
* 赠送礼物给其他用户
*/
public function send_gift($sender_id, $receiver_id, $gift_id, $quantity = 1, $message = '') {
global $wpdb;
// 检查接收者是否存在
$receiver = get_user_by('ID', $receiver_id);
if (!$receiver) {
return array('success' => false, 'message' => '接收者不存在');
}
// 不能送给自己
if ($sender_id == $receiver_id) {
return array('success' => false, 'message' => '不能给自己赠送礼物');
}
// 先购买礼物
$purchase_result = $this->purchase_gift($sender_id, $gift_id, $quantity);
if (!$purchase_result['success']) {
return $purchase_result;
}
// 记录礼物交易
$transactions_table = $wpdb->prefix . 'gift_transactions';
$wpdb->insert(
$transactions_table,
array(
'sender_id' => $sender_id,
'receiver_id' => $receiver_id,
'gift_id' => $gift_id,
'quantity' => $quantity,
'message' => $message
),
array('%d', '%d', '%d', '%d', '%s')
);
$transaction_id = $wpdb->insert_id;
// 发送通知给接收者
$this->send_gift_notification($sender_id, $receiver_id, $gift_id, $quantity, $message);
return array(
'success' => true,
'message' => '礼物赠送成功',
'transaction_id' => $transaction_id
);
}
/**
* 发送礼物通知
*/
private function send_gift_notification($sender_id, $receiver_id, $gift_id, $quantity, $message) {
$sender = get_user_by('ID', $sender_id);
$gift = $this->get_gift($gift_id);
$notification = sprintf(
'%s 向您赠送了 %d 个「%s」',
$sender->display_name,
$quantity,
$gift->gift_name
);
if (!empty($message)) {
$notification .= sprintf(',并留言:%s', $message);
}
// 使用WordPress的通知系统或自定义通知
if (function_exists('bp_notifications_add_notification')) {
// BuddyPress通知
bp_notifications_add_notification(array(
'user_id' => $receiver_id,
'item_id' => $gift_id,
'component_name' => 'gifts',
'component_action' => 'new_gift',
'date_notified' => bp_core_current_time(),
'is_new' => 1,
));
}
// 发送站内信
$this->send_private_message($sender_id, $receiver_id, $notification);
// 发送邮件通知
$receiver_email = get_user_by('ID', $receiver_id)->user_email;
$subject = '您收到了一份新礼物';
wp_mail($receiver_email, $subject, $notification);
}
/**
* 发送站内私信
*/
private function send_private_message($sender_id, $receiver_id, $message) {
// 这里可以集成站内信系统
// 如果使用BuddyPress,可以使用bp_messages_new_message函数
// 或者使用自定义的站内信系统
}
/**
* 获取用户收到的礼物
*/
public function get_received_gifts($user_id, $limit = 20, $offset = 0) {
global $wpdb;
$transactions_table = $wpdb->prefix . 'gift_transactions';
$gifts_table = $wpdb->prefix . 'virtual_gifts';
$users_table = $wpdb->prefix . 'users';
$gifts = $wpdb->get_results($wpdb->prepare(
"SELECT t.*, g.gift_name, g.gift_image, u.display_name as sender_name
FROM $transactions_table t
INNER JOIN $gifts_table g ON t.gift_id = g.id
INNER JOIN $users_table u ON t.sender_id = u.ID
WHERE t.receiver_id = %d
ORDER BY t.created_at DESC
LIMIT %d OFFSET %d",
$user_id, $limit, $offset
));
return $gifts;
}
/**
* 获取用户送出的礼物
*/
public function get_sent_gifts($user_id, $limit = 20, $offset = 0) {
global $wpdb;
$transactions_table = $wpdb->prefix . 'gift_transactions';
$gifts_table = $wpdb->prefix . 'virtual_gifts';
$users_table = $wpdb->prefix . 'users';
$gifts = $wpdb->get_results($wpdb->prepare(
"SELECT t.*, g.gift_name, g.gift_image, u.display_name as receiver_name
FROM $transactions_table t
INNER JOIN $gifts_table g ON t.gift_id = g.id
INNER JOIN $users_table u ON t.receiver_id = u.ID
WHERE t.sender_id = %d
ORDER BY t.created_at DESC
LIMIT %d OFFSET %d",
$user_id, $limit, $offset
));
return $gifts;
}
/**
* AJAX处理:购买礼物
*/
public function ajax_purchase_gift() {
// 安全检查
check_ajax_referer('gift_nonce', 'nonce');
if (!is_user_logged_in()) {
wp_die(json_encode(array(
'success' => false,
'message' => '请先登录'
)));
}
$user_id = get_current_user_id();
$gift_id = intval($_POST['gift_id']);
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
if ($quantity < 1) {
$quantity = 1;
}
$result = $this->purchase_gift($user_id, $gift_id, $quantity);
wp_die(json_encode($result));
}
/**
* AJAX处理:赠送礼物
*/
public function ajax_send_gift() {
// 安全检查
check_ajax_referer('gift_nonce', 'nonce');
if (!is_user_logged_in()) {
wp_die(json_encode(array(
'success' => false,
'message' => '请先登录'
)));
}
$sender_id = get_current_user_id();
$receiver_id = intval($_POST['receiver_id']);
$gift_id = intval($_POST['gift_id']);
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
$message = isset($_POST['message']) ? sanitize_text_field($_POST['message']) : '';
$result = $this->send_gift($sender_id, $receiver_id, $gift_id, $quantity, $message);
wp_die(json_encode($result));
}
/**
* 无权限的AJAX请求处理
*/
public function ajax_no_permission() {
wp_die(json_encode(array(
'success' => false,
'message' => '无权限操作'
)));
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_menu_page(
'虚拟礼物管理',
'虚拟礼物',
'manage_options',
'virtual-gifts',
array($this, 'gifts_admin_page'),
'dashicons-games',
30
);
add_submenu_page(
'virtual-gifts',
'礼物管理',
'礼物列表',
'manage_options',
'virtual-gifts',
array($this, 'gifts_admin_page')
);
add_submenu_page(
'virtual-gifts',
'交易记录',
'交易记录',
'manage_options',
'gift-transactions',
array($this, 'transactions_admin_page')
);
}
/**
* 礼物管理页面
*/
public function gifts_admin_page() {
global $wpdb;
$gifts_table = $wpdb->prefix . 'virtual_gifts';
// 处理表单提交
if (isset($_POST['add_gift'])) {
$this->handle_add_gift();
} elseif (isset($_POST['update_gift'])) {
$this->handle_update_gift();
} elseif (isset($_GET['delete_gift'])) {
$this->handle_delete_gift();
}
// 获取所有礼物
$gifts = $wpdb->get_results("SELECT * FROM $gifts_table ORDER BY sort_order ASC");
?>
<div class="wrap">
<h1>虚拟礼物管理</h1>
<h2>添加新礼物</h2>
<form method="post" action="">
<?php wp_nonce_field('gift_management', 'gift_nonce'); ?>
<table class="form-table">
<tr>
<th><label for="gift_name">礼物名称</label></th>
<td><input type="text" id="gift_name" name="gift_name" required class="regular-text"></td>
</tr>
<tr>
<th><label for="gift_description">描述</label></th>
<td><textarea id="gift_description" name="gift_description" rows="3" class="large-text"></textarea></td>
</tr>
<tr>
<th><label for="gift_price">价格(积分)</label></th>
<td><input type="number" id="gift_price" name="gift_price" required min="1" class="small-text"></td>
</tr>
<tr>
<th><label for="gift_category">分类</label></th>
<td><input type="text" id="gift_category" name="gift_category" class="regular-text"></td>
</tr>
<tr>
<th><label for="sort_order">排序</label></th>
<td><input type="number" id="sort_order" name="sort_order" value="0" class="small-text"></td>
</tr>
</table>
<p class="submit">
<input type="submit" name="add_gift"
