文章目录[隐藏]
详细指南:开发WordPress网站会员积分与等级系统
引言:为什么需要会员积分与等级系统?
在当今竞争激烈的互联网环境中,网站用户留存和活跃度已成为衡量网站成功的重要指标。会员积分与等级系统作为一种成熟的用户激励策略,能够有效提升用户参与度、增加用户粘性,并最终促进网站的商业转化。无论是电商平台、内容社区还是在线教育网站,一个设计良好的积分等级系统都能显著提升用户体验和忠诚度。
WordPress作为全球最流行的内容管理系统,拥有强大的扩展性和灵活性。通过代码二次开发,我们可以在WordPress网站上实现功能完善的会员积分与等级系统,而无需依赖昂贵的第三方插件。本指南将详细介绍如何从零开始,通过代码开发实现这一系统。
第一章:系统设计与规划
1.1 确定系统目标与功能需求
在开始编码之前,我们需要明确积分等级系统的核心目标:
- 用户激励:鼓励用户完成特定行为(发布内容、评论、登录等)
- 用户分层:根据用户活跃度划分不同等级,提供差异化权益
- 数据收集:获取用户行为数据,为后续运营决策提供支持
- 社区建设:促进用户互动,形成良性竞争氛围
基于这些目标,我们规划以下核心功能:
- 积分获取规则:定义用户可通过哪些行为获得积分
- 等级划分体系:设置多个用户等级及升级条件
- 特权与权益:不同等级用户享有不同特权
- 积分消耗机制:用户可使用积分兑换礼品或特权
- 数据统计与展示:用户可查看自己的积分、等级和排名
1.2 数据库结构设计
我们需要在WordPress现有数据库基础上,添加以下自定义表:
-- 用户积分表
CREATE TABLE wp_user_points (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT(20) NOT NULL,
points INT DEFAULT 0,
total_points 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_user_levels (
id INT AUTO_INCREMENT PRIMARY KEY,
level_name VARCHAR(50) NOT NULL,
level_num INT NOT NULL,
min_points INT NOT NULL,
max_points INT,
privileges TEXT,
badge_url VARCHAR(255)
);
-- 用户等级关系表
CREATE TABLE wp_user_level_relations (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT(20) NOT NULL,
level_id INT NOT NULL,
achieved_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES wp_users(ID) ON DELETE CASCADE,
FOREIGN KEY (level_id) REFERENCES wp_user_levels(id) ON DELETE CASCADE
);
1.3 系统架构设计
我们的积分等级系统将采用以下架构:
- 核心管理层:处理积分计算、等级评定等核心逻辑
- 行为监听层:监听用户行为并触发积分奖励
- 数据存储层:管理积分和等级数据的存储与检索
- 前端展示层:向用户展示积分、等级和排名信息
- 管理界面层:为管理员提供系统配置和监控功能
第二章:开发环境搭建与基础配置
2.1 创建自定义插件
为了避免主题更新导致代码丢失,我们将创建一个独立的WordPress插件:
<?php
/**
* Plugin Name: 会员积分与等级系统
* Plugin URI: https://yourwebsite.com/
* Description: 为WordPress网站添加会员积分与等级功能
* Version: 1.0.0
* Author: Your Name
* License: GPL v2 or later
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('MPL_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('MPL_PLUGIN_URL', plugin_dir_url(__FILE__));
define('MPL_VERSION', '1.0.0');
// 包含必要文件
require_once MPL_PLUGIN_DIR . 'includes/class-database.php';
require_once MPL_PLUGIN_DIR . 'includes/class-points-manager.php';
require_once MPL_PLUGIN_DIR . 'includes/class-levels-manager.php';
require_once MPL_PLUGIN_DIR . 'includes/class-actions-listener.php';
require_once MPL_PLUGIN_DIR . 'includes/class-shortcodes.php';
require_once MPL_PLUGIN_DIR . 'includes/class-admin-panel.php';
2.2 数据库表创建与更新
创建数据库管理类,负责表的创建和更新:
<?php
// includes/class-database.php
class MPL_Database {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
// 注册激活钩子
register_activation_hook(__FILE__, array($this, 'create_tables'));
// 注册更新检查
add_action('plugins_loaded', array($this, 'check_for_updates'));
}
public function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
// 用户积分表
$table_points = $wpdb->prefix . 'user_points';
$sql_points = "CREATE TABLE IF NOT EXISTS $table_points (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT(20) NOT NULL,
points INT DEFAULT 0,
total_points INT DEFAULT 0,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY user_id (user_id)
) $charset_collate;";
// 积分记录表
$table_log = $wpdb->prefix . 'points_log';
$sql_log = "CREATE TABLE IF NOT EXISTS $table_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,
KEY user_id (user_id),
KEY action_type (action_type)
) $charset_collate;";
// 用户等级表
$table_levels = $wpdb->prefix . 'user_levels';
$sql_levels = "CREATE TABLE IF NOT EXISTS $table_levels (
id INT AUTO_INCREMENT PRIMARY KEY,
level_name VARCHAR(50) NOT NULL,
level_num INT NOT NULL,
min_points INT NOT NULL,
max_points INT,
privileges TEXT,
badge_url VARCHAR(255),
UNIQUE KEY level_num (level_num)
) $charset_collate;";
// 用户等级关系表
$table_level_relations = $wpdb->prefix . 'user_level_relations';
$sql_level_relations = "CREATE TABLE IF NOT EXISTS $table_level_relations (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT(20) NOT NULL,
level_id INT NOT NULL,
achieved_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY user_level (user_id, level_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql_points);
dbDelta($sql_log);
dbDelta($sql_levels);
dbDelta($sql_level_relations);
// 插入默认等级数据
$this->insert_default_levels();
// 设置插件版本
update_option('mpl_db_version', MPL_VERSION);
}
private function insert_default_levels() {
global $wpdb;
$table_levels = $wpdb->prefix . 'user_levels';
// 检查是否已有数据
$count = $wpdb->get_var("SELECT COUNT(*) FROM $table_levels");
if ($count == 0) {
$default_levels = array(
array('level_name' => '新手', 'level_num' => 1, 'min_points' => 0, 'max_points' => 100),
array('level_name' => '初级会员', 'level_num' => 2, 'min_points' => 101, 'max_points' => 500),
array('level_name' => '中级会员', 'level_num' => 3, 'min_points' => 501, 'max_points' => 2000),
array('level_name' => '高级会员', 'level_num' => 4, 'min_points' => 2001, 'max_points' => 10000),
array('level_name' => '至尊会员', 'level_num' => 5, 'min_points' => 10001, 'max_points' => NULL),
);
foreach ($default_levels as $level) {
$wpdb->insert($table_levels, $level);
}
}
}
public function check_for_updates() {
$current_version = get_option('mpl_db_version', '0');
if (version_compare($current_version, MPL_VERSION, '<')) {
$this->create_tables();
}
}
}
第三章:核心功能开发
3.1 积分管理类实现
积分管理类是系统的核心,负责处理所有与积分相关的操作:
<?php
// includes/class-points-manager.php
class MPL_Points_Manager {
private static $instance = null;
private $actions_points = array();
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
// 初始化积分规则
$this->init_points_rules();
// 添加用户注册时初始化积分记录
add_action('user_register', array($this, 'init_user_points'));
// 添加删除用户时清理积分记录
add_action('delete_user', array($this, 'delete_user_points'));
}
private function init_points_rules() {
// 定义各种行为对应的积分值
$this->actions_points = array(
'user_register' => 100, // 注册账号
'daily_login' => 10, // 每日登录
'publish_post' => 50, // 发布文章
'publish_comment' => 5, // 发表评论
'comment_approved' => 10, // 评论被审核通过
'post_liked' => 2, // 文章被点赞
'comment_liked' => 1, // 评论被点赞
'post_shared' => 20, // 分享文章
'profile_completed' => 30, // 完善个人资料
'referral_user' => 200, // 推荐用户注册
);
// 允许通过过滤器修改积分规则
$this->actions_points = apply_filters('mpl_points_rules', $this->actions_points);
}
public function init_user_points($user_id) {
global $wpdb;
$table_points = $wpdb->prefix . 'user_points';
// 检查用户是否已有积分记录
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $table_points WHERE user_id = %d",
$user_id
));
if (!$existing) {
$wpdb->insert($table_points, array(
'user_id' => $user_id,
'points' => 0,
'total_points' => 0
));
// 为新用户添加注册积分
$this->add_points($user_id, 'user_register', $user_id);
}
}
public function add_points($user_id, $action_type, $related_id = null, $description = '') {
global $wpdb;
// 检查用户是否存在
if (!get_userdata($user_id)) {
return false;
}
// 获取该行为对应的积分值
$points = isset($this->actions_points[$action_type]) ?
$this->actions_points[$action_type] : 0;
if ($points <= 0) {
return false;
}
// 检查今日是否已获得过该类型积分(防止刷分)
if ($this->is_action_limited($user_id, $action_type)) {
return false;
}
$table_points = $wpdb->prefix . 'user_points';
$table_log = $wpdb->prefix . 'points_log';
// 开始事务
$wpdb->query('START TRANSACTION');
try {
// 更新用户总积分
$result = $wpdb->query($wpdb->prepare(
"UPDATE $table_points
SET points = points + %d, total_points = total_points + %d
WHERE user_id = %d",
$points, $points, $user_id
));
if ($result === false) {
throw new Exception('更新用户积分失败');
}
// 记录积分日志
$log_data = array(
'user_id' => $user_id,
'points_change' => $points,
'action_type' => $action_type,
'related_id' => $related_id,
'description' => $description ?: $this->get_action_description($action_type)
);
$log_result = $wpdb->insert($table_log, $log_data);
if ($log_result === false) {
throw new Exception('记录积分日志失败');
}
// 提交事务
$wpdb->query('COMMIT');
// 触发积分添加钩子
do_action('mpl_points_added', $user_id, $points, $action_type, $related_id);
// 检查用户等级是否需要更新
$this->check_user_level($user_id);
return true;
} catch (Exception $e) {
// 回滚事务
$wpdb->query('ROLLBACK');
error_log('MPL积分系统错误: ' . $e->getMessage());
return false;
}
}
public function deduct_points($user_id, $points, $reason, $related_id = null) {
global $wpdb;
if ($points <= 0) {
return false;
}
$table_points = $wpdb->prefix . 'user_points';
// 检查用户是否有足够积分
$current_points = $this->get_user_points($user_id);
if ($current_points < $points) {
return false;
}
// 开始事务
$wpdb->query('START TRANSACTION');
try {
// 扣除积分
$result = $wpdb->query($wpdb->prepare(
"UPDATE $table_points SET points = points - %d WHERE user_id = %d",
$points, $user_id
));
if ($result === false) {
throw new Exception('扣除用户积分失败');
}
// 记录积分日志(负值表示扣除)
$table_log = $wpdb->prefix . 'points_log';
$log_data = array(
'user_id' => $user_id,
'points_change' => -$points,
'action_type' => 'points_deducted',
'related_id' => $related_id,
'description' => $reason
);
$log_result = $wpdb->insert($table_log, $log_data);
if ($log_result === false) {
throw new Exception('记录积分扣除日志失败');
}
// 提交事务
$wpdb->query('COMMIT');
// 触发积分扣除钩子
do_action('mpl_points_deducted', $user_id, $points, $reason, $related_id);
return true;
} catch (Exception $e) {
// 回滚事务
$wpdb->query('ROLLBACK');
error_log('MPL积分系统错误: ' . $e->getMessage());
return false;
}
}
public function get_user_points($user_id) {
global $wpdb;
$table_points = $wpdb->prefix . 'user_points';
$points = $wpdb->get_var($wpdb->prepare(
"SELECT points FROM $table_points WHERE user_id = %d",
$user_id
));
return $points ? intval($points) : 0;
}
public function get_user_total_points($user_id) {
global $wpdb;
$table_points = $wpdb->prefix . 'user_points';
$total_points = $wpdb->get_var($wpdb->prepare(
"SELECT total_points FROM $table_points WHERE user_id = %d",
$user_id
));
return $total_points ? intval($total_points) : 0;
}
public function get_points_log($user_id, $limit = 20, $offset = 0) {
global $wpdb;
$table_log = $wpdb->prefix . 'points_log';
$logs = $wpdb->get_results($wpdb->prepare(
"SELECT * FROM $table_log
WHERE user_id = %d
ORDER BY created_at DESC
LIMIT %d OFFSET %d",
$user_id, $limit, $offset
));
return $logs;
}
private function is_action_limited($user_id, $action_type) {
// 对于某些行为,限制每日获取次数
3.2 等级管理类实现
等级管理类负责处理用户等级评定、升级逻辑和特权管理:
<?php
// includes/class-levels-manager.php
class MPL_Levels_Manager {
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('mpl_points_added', array($this, 'check_user_level_on_points_change'), 10, 2);
}
public function check_user_level($user_id) {
global $wpdb;
$points_manager = MPL_Points_Manager::get_instance();
$current_points = $points_manager->get_user_points($user_id);
// 获取用户当前等级
$current_level = $this->get_user_level($user_id);
// 获取所有等级定义
$levels = $this->get_all_levels();
// 根据积分确定应属等级
$target_level = null;
foreach ($levels as $level) {
if ($current_points >= $level->min_points &&
($level->max_points === null || $current_points <= $level->max_points)) {
$target_level = $level;
break;
}
}
// 如果用户没有等级或需要升级
if (!$current_level || ($target_level && $target_level->level_num > $current_level->level_num)) {
$this->update_user_level($user_id, $target_level->id);
// 触发等级升级钩子
do_action('mpl_level_upgraded', $user_id, $current_level, $target_level);
// 发送升级通知
$this->send_level_up_notification($user_id, $target_level);
return true;
}
return false;
}
public function get_user_level($user_id) {
global $wpdb;
$table_level_relations = $wpdb->prefix . 'user_level_relations';
$table_levels = $wpdb->prefix . 'user_levels';
$level = $wpdb->get_row($wpdb->prepare(
"SELECT l.* FROM $table_levels l
INNER JOIN $table_level_relations r ON l.id = r.level_id
WHERE r.user_id = %d
ORDER BY l.level_num DESC
LIMIT 1",
$user_id
));
return $level;
}
public function update_user_level($user_id, $level_id) {
global $wpdb;
$table_level_relations = $wpdb->prefix . 'user_level_relations';
// 检查是否已拥有该等级
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $table_level_relations
WHERE user_id = %d AND level_id = %d",
$user_id, $level_id
));
if (!$existing) {
$wpdb->insert($table_level_relations, array(
'user_id' => $user_id,
'level_id' => $level_id
));
return true;
}
return false;
}
public function get_all_levels() {
global $wpdb;
$table_levels = $wpdb->prefix . 'user_levels';
$levels = $wpdb->get_results(
"SELECT * FROM $table_levels ORDER BY level_num ASC"
);
return $levels;
}
public function get_level_by_points($points) {
global $wpdb;
$table_levels = $wpdb->prefix . 'user_levels';
$level = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $table_levels
WHERE min_points <= %d AND (max_points >= %d OR max_points IS NULL)
ORDER BY level_num DESC
LIMIT 1",
$points, $points
));
return $level;
}
public function get_next_level($current_level_num) {
global $wpdb;
$table_levels = $wpdb->prefix . 'user_levels';
$next_level = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $table_levels
WHERE level_num > %d
ORDER BY level_num ASC
LIMIT 1",
$current_level_num
));
return $next_level;
}
public function get_level_progress($user_id) {
$points_manager = MPL_Points_Manager::get_instance();
$current_points = $points_manager->get_user_points($user_id);
$current_level = $this->get_user_level($user_id);
$next_level = $this->get_next_level($current_level->level_num);
if (!$next_level) {
return array(
'current_level' => $current_level,
'next_level' => null,
'progress_percentage' => 100,
'points_to_next' => 0,
'current_points' => $current_points
);
}
$points_range = $next_level->min_points - $current_level->min_points;
$points_in_current = $current_points - $current_level->min_points;
$progress_percentage = $points_range > 0 ?
min(100, round(($points_in_current / $points_range) * 100, 2)) : 0;
$points_to_next = max(0, $next_level->min_points - $current_points);
return array(
'current_level' => $current_level,
'next_level' => $next_level,
'progress_percentage' => $progress_percentage,
'points_to_next' => $points_to_next,
'current_points' => $current_points
);
}
public function get_level_privileges($level_id) {
global $wpdb;
$table_levels = $wpdb->prefix . 'user_levels';
$privileges_json = $wpdb->get_var($wpdb->prepare(
"SELECT privileges FROM $table_levels WHERE id = %d",
$level_id
));
if ($privileges_json) {
return json_decode($privileges_json, true);
}
return array();
}
public function check_user_privilege($user_id, $privilege_key) {
$user_level = $this->get_user_level($user_id);
if (!$user_level) {
return false;
}
$privileges = $this->get_level_privileges($user_level->id);
return isset($privileges[$privilege_key]) && $privileges[$privilege_key] === true;
}
private function send_level_up_notification($user_id, $new_level) {
$user = get_userdata($user_id);
if (!$user) {
return;
}
$subject = sprintf('恭喜!您已升级为%s', $new_level->level_name);
$message = sprintf(
"亲爱的%s,nn恭喜您!您的会员等级已提升至【%s】。nn" .
"这是对您长期支持的认可,您现在可以享受更多专属特权。nn" .
"继续努力,向更高等级迈进吧!nn" .
"祝您使用愉快!n%s团队",
$user->display_name,
$new_level->level_name,
get_bloginfo('name')
);
wp_mail($user->user_email, $subject, $message);
// 同时发送站内通知
if (function_exists('bp_notifications_add_notification')) {
// 如果使用BuddyPress,添加通知
bp_notifications_add_notification(array(
'user_id' => $user_id,
'item_id' => $new_level->id,
'secondary_item_id' => 0,
'component_name' => 'mpl_points',
'component_action' => 'level_upgraded',
'date_notified' => bp_core_current_time(),
'is_new' => 1,
));
}
}
public function check_user_level_on_points_change($user_id, $points_added) {
$this->check_user_level($user_id);
}
}
3.3 行为监听类实现
行为监听类负责监听用户的各种行为并触发相应的积分奖励:
<?php
// includes/class-actions-listener.php
class MPL_Actions_Listener {
private static $instance = null;
private $points_manager;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->points_manager = MPL_Points_Manager::get_instance();
// 初始化所有监听器
$this->init_listeners();
}
private function init_listeners() {
// 文章发布监听
add_action('publish_post', array($this, 'on_publish_post'), 10, 2);
// 评论发布监听
add_action('comment_post', array($this, 'on_comment_post'), 10, 3);
add_action('wp_set_comment_status', array($this, 'on_comment_approved'), 10, 2);
// 每日登录监听
add_action('wp_login', array($this, 'on_user_login'), 10, 2);
// 点赞系统集成(需要与点赞插件配合)
add_action('mpl_post_liked', array($this, 'on_post_liked'), 10, 2);
add_action('mpl_comment_liked', array($this, 'on_comment_liked'), 10, 2);
// 分享监听
add_action('mpl_content_shared', array($this, 'on_content_shared'), 10, 2);
// 个人资料完善监听
add_action('profile_update', array($this, 'on_profile_updated'), 10, 2);
// 推荐用户注册监听
add_action('user_register', array($this, 'on_referral_registration'), 10, 1);
}
public function on_publish_post($post_id, $post) {
// 确保是新建文章,而不是更新
if ($post->post_date !== $post->post_modified) {
return;
}
$user_id = $post->post_author;
$this->points_manager->add_points(
$user_id,
'publish_post',
$post_id,
sprintf('发布文章《%s》', get_the_title($post_id))
);
}
public function on_comment_post($comment_id, $comment_approved, $commentdata) {
if ($comment_approved == 1) {
$user_id = $commentdata['user_id'];
// 匿名评论没有用户ID
if ($user_id > 0) {
$this->points_manager->add_points(
$user_id,
'publish_comment',
$comment_id,
sprintf('发表评论于文章《%s》', get_the_title($commentdata['comment_post_ID']))
);
}
}
}
public function on_comment_approved($comment_id, $comment_status) {
if ($comment_status == 'approve') {
$comment = get_comment($comment_id);
if ($comment->user_id > 0) {
// 如果之前已经因为评论获得过积分,不再重复奖励
global $wpdb;
$table_log = $wpdb->prefix . 'points_log';
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $table_log
WHERE user_id = %d AND related_id = %d AND action_type = 'comment_approved'",
$comment->user_id, $comment_id
));
if (!$existing) {
$this->points_manager->add_points(
$comment->user_id,
'comment_approved',
$comment_id,
sprintf('评论在文章《%s》中被审核通过', get_the_title($comment->comment_post_ID))
);
}
}
}
}
public function on_user_login($user_login, $user) {
$user_id = $user->ID;
$today = date('Y-m-d');
// 检查今日是否已登录过
global $wpdb;
$table_log = $wpdb->prefix . 'points_log';
$already_logged_today = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $table_log
WHERE user_id = %d AND action_type = 'daily_login'
AND DATE(created_at) = %s",
$user_id, $today
));
if (!$already_logged_today) {
$this->points_manager->add_points(
$user_id,
'daily_login',
null,
'每日登录奖励'
);
}
}
public function on_post_liked($post_id, $user_id) {
$post_author = get_post_field('post_author', $post_id);
if ($post_author && $post_author != $user_id) {
$this->points_manager->add_points(
$post_author,
'post_liked',
$post_id,
sprintf('文章《%s》被用户点赞', get_the_title($post_id))
);
}
}
public function on_comment_liked($comment_id, $user_id) {
$comment = get_comment($comment_id);
if ($comment->user_id && $comment->user_id != $user_id) {
$this->points_manager->add_points(
$comment->user_id,
'comment_liked',
$comment_id,
'评论被用户点赞'
);
}
}
public function on_content_shared($content_id, $user_id) {
$content_type = get_post_type($content_id);
if ($content_type === 'post') {
$this->points_manager->add_points(
$user_id,
'post_shared',
$content_id,
sprintf('分享文章《%s》', get_the_title($content_id))
);
}
}
public function on_profile_updated($user_id, $old_user_data) {
$user = get_userdata($user_id);
$old_user = $old_user_data;
// 检查是否完善了个人资料
$profile_completed = false;
// 检查头像
if (get_user_meta($user_id, 'avatar_updated', true)) {
$profile_completed = true;
}
// 检查个人简介
if (!empty($user->description) && empty($old_user->description)) {
$profile_completed = true;
}
// 检查其他必填字段
$required_fields = array('first_name', 'last_name', 'user_url');
foreach ($required_fields as $field) {
if (!empty($user->$field) && empty($old_user->$field)) {
$profile_completed = true;
break;
}
}
if ($profile_completed) {
// 确保只奖励一次
$already_rewarded = get_user_meta($user_id, 'profile_completion_rewarded', true);
if (!$already_rewarded) {
$this->points_manager->add_points(
$user_id,
'profile_completed',
null,
'完善个人资料'
);
update_user_meta($user_id, 'profile_completion_rewarded', true);
}
}
}
public function on_referral_registration($user_id) {
// 检查是否有推荐人
$referrer_id = get_user_meta($user_id, 'referred_by', true);
if ($referrer_id) {
$this->points_manager->add_points(
$referrer_id,
'referral_user',
$user_id,
sprintf('成功推荐用户 %s 注册', get_userdata($user_id)->display_name)
);
}
}
}
第四章:前端展示与用户界面
4.1 短代码类实现
短代码类提供前端展示功能,让用户可以在任何页面查看积分和等级信息:
<?php
// includes/class-shortcodes.php
class MPL_Shortcodes {
private static $instance = null;
private $points_manager;
private $levels_manager;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->points_manager = MPL_Points_Manager::get_instance();
$this->levels_manager = MPL_Levels_Manager::get_instance();
// 注册短代码
add_shortcode('mpl_user_points', array($this, 'user_points_shortcode'));
add_shortcode('mpl_user_level', array($this, 'user_level_shortcode'));
add_shortcode('mpl_level_progress', array($this, 'level_progress_shortcode'));
add_shortcode('mpl_points_log', array($this, 'points_log_shortcode'));
add_shortcode('mpl_leaderboard', array($this, 'leaderboard_shortcode'));
add_shortcode('mpl_levels_list', array($this, 'levels_list_shortcode'));
// 注册样式和脚本
add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets'));
}
public function enqueue_frontend_assets() {
wp_enqueue_style(
'mpl-frontend',
MPL_PLUGIN_URL . 'assets/css/frontend.css',
array(),
MPL_VERSION
);
wp_enqueue_script(
'mpl-frontend',
