首页 / 应用软件 / WordPress开发教程,集成网站用户贡献内容积分兑换商城系统

WordPress开发教程,集成网站用户贡献内容积分兑换商城系统

WordPress开发教程:集成用户贡献内容积分兑换商城系统与常用互联网小工具功能

引言:WordPress的无限可能性

在当今数字化时代,网站已不仅仅是信息展示的平台,更是用户互动和参与的重要场所。WordPress作为全球最受欢迎的内容管理系统,其真正的强大之处在于其高度的可扩展性和灵活性。本教程将深入探讨如何通过WordPress代码二次开发,实现一个集用户贡献内容、积分系统和兑换商城于一体的综合性平台,同时集成多种实用互联网小工具功能。

通过本教程,您将学习到如何将WordPress从一个简单的博客平台转变为一个功能丰富的互动社区和电子商务系统。无论您是WordPress开发者、网站管理员还是希望扩展网站功能的创业者,这些知识都将为您打开新的可能性。

第一部分:项目规划与环境搭建

1.1 系统需求分析与功能规划

在开始开发之前,我们需要明确项目的核心需求:

  1. 用户贡献内容系统:允许用户提交文章、评论、图片等内容
  2. 积分管理系统:根据用户行为自动计算和分配积分
  3. 积分兑换商城:用户可以使用积分兑换实物或虚拟商品
  4. 常用互联网小工具:集成实用工具如短链接生成、二维码创建等

技术架构规划:

  • 主框架:WordPress 5.8+
  • 开发方式:自定义插件+主题二次开发
  • 数据库:MySQL 5.6+
  • 前端技术:HTML5, CSS3, JavaScript (jQuery/Vue.js)
  • 安全考虑:数据验证、SQL注入防护、XSS防护

1.2 开发环境配置

首先,确保您的开发环境满足以下要求:

// 检查WordPress环境要求
define('WP_DEBUG', true); // 开发阶段开启调试模式
define('WP_DEBUG_LOG', true); // 将错误记录到日志
define('WP_DEBUG_DISPLAY', false); // 不直接显示错误

// 推荐服务器配置
// PHP版本:7.4或更高
// MySQL版本:5.6或更高
// 内存限制:至少256MB

安装必要的开发工具:

  1. 本地服务器环境(XAMPP、MAMP或Local by Flywheel)
  2. 代码编辑器(VS Code、PHPStorm等)
  3. Git版本控制系统
  4. 浏览器开发者工具

1.3 创建自定义插件基础结构

我们将创建一个主插件来管理所有功能:

/*
Plugin Name: 用户积分商城系统
Plugin URI: https://yourwebsite.com/
Description: 集成用户贡献内容、积分系统和兑换商城的综合解决方案
Version: 1.0.0
Author: 您的名称
License: GPL v2 or later
Text Domain: user-points-mall
*/

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('UPM_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('UPM_PLUGIN_URL', plugin_dir_url(__FILE__));
define('UPM_VERSION', '1.0.0');

// 初始化插件
function upm_init() {
    // 加载语言文件
    load_plugin_textdomain('user-points-mall', false, dirname(plugin_basename(__FILE__)) . '/languages');
    
    // 检查依赖
    upm_check_dependencies();
}
add_action('plugins_loaded', 'upm_init');

// 检查系统依赖
function upm_check_dependencies() {
    $errors = array();
    
    // 检查PHP版本
    if (version_compare(PHP_VERSION, '7.4', '<')) {
        $errors[] = __('需要PHP 7.4或更高版本', 'user-points-mall');
    }
    
    // 检查WordPress版本
    if (version_compare(get_bloginfo('version'), '5.8', '<')) {
        $errors[] = __('需要WordPress 5.8或更高版本', 'user-points-mall');
    }
    
    // 如果有错误,显示通知
    if (!empty($errors)) {
        add_action('admin_notices', function() use ($errors) {
            echo '<div class="notice notice-error"><p>';
            echo __('用户积分商城系统插件无法激活:', 'user-points-mall');
            echo '<ul>';
            foreach ($errors as $error) {
                echo '<li>' . $error . '</li>';
            }
            echo '</ul></p></div>';
        });
        
        // 停用插件
        deactivate_plugins(plugin_basename(__FILE__));
    }
}

第二部分:用户贡献内容系统开发

2.1 自定义文章类型与用户提交表单

创建用户贡献内容系统,首先需要定义自定义文章类型:

// 注册用户贡献内容类型
function upm_register_contribution_type() {
    $labels = array(
        'name'               => __('用户贡献', 'user-points-mall'),
        'singular_name'      => __('贡献内容', 'user-points-mall'),
        'menu_name'          => __('用户贡献', 'user-points-mall'),
        'add_new'            => __('添加新贡献', 'user-points-mall'),
        'add_new_item'       => __('添加新贡献内容', 'user-points-mall'),
        'edit_item'          => __('编辑贡献内容', 'user-points-mall'),
        'new_item'           => __('新贡献内容', 'user-points-mall'),
        'view_item'          => __('查看贡献内容', 'user-points-mall'),
        'search_items'       => __('搜索贡献内容', 'user-points-mall'),
        'not_found'          => __('未找到贡献内容', 'user-points-mall'),
        'not_found_in_trash' => __('回收站中无贡献内容', 'user-points-mall'),
    );
    
    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'contribution'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 5,
        'menu_icon'          => 'dashicons-groups',
        'supports'           => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),
        'show_in_rest'       => true, // 支持Gutenberg编辑器
    );
    
    register_post_type('user_contribution', $args);
}
add_action('init', 'upm_register_contribution_type');

// 添加贡献状态分类
function upm_register_contribution_status() {
    $labels = array(
        'name'              => __('贡献状态', 'user-points-mall'),
        'singular_name'     => __('状态', 'user-points-mall'),
        'search_items'      => __('搜索状态', 'user-points-mall'),
        'all_items'         => __('所有状态', 'user-points-mall'),
        'parent_item'       => __('父状态', 'user-points-mall'),
        'parent_item_colon' => __('父状态:', 'user-points-mall'),
        'edit_item'         => __('编辑状态', 'user-points-mall'),
        'update_item'       => __('更新状态', 'user-points-mall'),
        'add_new_item'      => __('添加新状态', 'user-points-mall'),
        'new_item_name'     => __('新状态名称', 'user-points-mall'),
        'menu_name'         => __('贡献状态', 'user-points-mall'),
    );
    
    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'contribution-status'),
        'show_in_rest'      => true,
    );
    
    register_taxonomy('contribution_status', array('user_contribution'), $args);
    
    // 默认状态
    $default_statuses = array(
        'pending'   => __('待审核', 'user-points-mall'),
        'approved'  => __('已通过', 'user-points-mall'),
        'rejected'  => __('已拒绝', 'user-points-mall'),
        'published' => __('已发布', 'user-points-mall'),
    );
    
    foreach ($default_statuses as $slug => $name) {
        if (!term_exists($name, 'contribution_status')) {
            wp_insert_term($name, 'contribution_status', array('slug' => $slug));
        }
    }
}
add_action('init', 'upm_register_contribution_status');

2.2 前端用户提交表单

创建用户提交贡献内容的前端表单:

// 短代码生成用户提交表单
function upm_contribution_form_shortcode($atts) {
    // 只有登录用户才能提交
    if (!is_user_logged_in()) {
        return '<div class="upm-alert upm-alert-warning">' . 
               __('请先登录后再提交贡献内容。', 'user-points-mall') . 
               ' <a href="' . wp_login_url(get_permalink()) . '">' . 
               __('登录', 'user-points-mall') . '</a></div>';
    }
    
    // 处理表单提交
    $message = '';
    $success = false;
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upm_contribution_nonce'])) {
        if (wp_verify_nonce($_POST['upm_contribution_nonce'], 'upm_submit_contribution')) {
            $result = upm_process_contribution_submission($_POST);
            
            if ($result['success']) {
                $message = '<div class="upm-alert upm-alert-success">' . 
                          __('贡献提交成功!内容正在审核中。', 'user-points-mall') . '</div>';
                $success = true;
            } else {
                $message = '<div class="upm-alert upm-alert-error">' . 
                          $result['message'] . '</div>';
            }
        } else {
            $message = '<div class="upm-alert upm-alert-error">' . 
                      __('安全验证失败,请重试。', 'user-points-mall') . '</div>';
        }
    }
    
    // 如果提交成功,显示成功消息
    if ($success) {
        return $message;
    }
    
    // 输出表单
    ob_start();
    ?>
    <div class="upm-contribution-form-wrapper">
        <?php echo $message; ?>
        
        <form id="upm-contribution-form" method="post" enctype="multipart/form-data">
            <?php wp_nonce_field('upm_submit_contribution', 'upm_contribution_nonce'); ?>
            
            <div class="upm-form-group">
                <label for="upm-contribution-title"><?php _e('标题', 'user-points-mall'); ?> *</label>
                <input type="text" id="upm-contribution-title" name="contribution_title" 
                       required class="upm-form-control" 
                       value="<?php echo isset($_POST['contribution_title']) ? esc_attr($_POST['contribution_title']) : ''; ?>">
            </div>
            
            <div class="upm-form-group">
                <label for="upm-contribution-content"><?php _e('内容', 'user-points-mall'); ?> *</label>
                <?php 
                $content = isset($_POST['contribution_content']) ? wp_kses_post($_POST['contribution_content']) : '';
                wp_editor($content, 'upm-contribution-content', array(
                    'textarea_name' => 'contribution_content',
                    'textarea_rows' => 10,
                    'media_buttons' => true,
                    'teeny' => false,
                    'quicktags' => true
                )); 
                ?>
            </div>
            
            <div class="upm-form-group">
                <label for="upm-contribution-excerpt"><?php _e('摘要', 'user-points-mall'); ?></label>
                <textarea id="upm-contribution-excerpt" name="contribution_excerpt" 
                          class="upm-form-control" rows="3"><?php echo isset($_POST['contribution_excerpt']) ? esc_textarea($_POST['contribution_excerpt']) : ''; ?></textarea>
            </div>
            
            <div class="upm-form-group">
                <label for="upm-contribution-thumbnail"><?php _e('特色图片', 'user-points-mall'); ?></label>
                <input type="file" id="upm-contribution-thumbnail" name="contribution_thumbnail" 
                       accept="image/*" class="upm-form-control">
                <p class="upm-help-text"><?php _e('支持JPG、PNG格式,最大2MB', 'user-points-mall'); ?></p>
            </div>
            
            <div class="upm-form-group">
                <label for="upm-contribution-category"><?php _e('分类', 'user-points-mall'); ?></label>
                <select id="upm-contribution-category" name="contribution_category" class="upm-form-control">
                    <option value=""><?php _e('选择分类', 'user-points-mall'); ?></option>
                    <?php
                    $categories = get_categories(array('hide_empty' => false));
                    foreach ($categories as $category) {
                        $selected = (isset($_POST['contribution_category']) && $_POST['contribution_category'] == $category->term_id) ? 'selected' : '';
                        echo '<option value="' . $category->term_id . '" ' . $selected . '>' . 
                             esc_html($category->name) . '</option>';
                    }
                    ?>
                </select>
            </div>
            
            <div class="upm-form-group">
                <label>
                    <input type="checkbox" name="agree_terms" required>
                    <?php _e('我同意遵守网站内容提交规则', 'user-points-mall'); ?>
                </label>
            </div>
            
            <div class="upm-form-group">
                <input type="submit" name="submit_contribution" 
                       value="<?php _e('提交贡献', 'user-points-mall'); ?>" 
                       class="upm-btn upm-btn-primary">
            </div>
        </form>
    </div>
    
    <style>
    .upm-contribution-form-wrapper {
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background: #f9f9f9;
        border-radius: 8px;
    }
    .upm-form-group {
        margin-bottom: 20px;
    }
    .upm-form-control {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-sizing: border-box;
    }
    .upm-btn {
        padding: 12px 24px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
    }
    .upm-btn-primary {
        background: #0073aa;
        color: white;
    }
    .upm-alert {
        padding: 15px;
        margin-bottom: 20px;
        border-radius: 4px;
    }
    .upm-alert-success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .upm-alert-error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    .upm-alert-warning {
        background: #fff3cd;
        color: #856404;
        border: 1px solid #ffeaa7;
    }
    </style>
    <?php
    return ob_get_clean();
}
add_shortcode('upm_contribution_form', 'upm_contribution_form_shortcode');

// 处理表单提交
function upm_process_contribution_submission($data) {
    $result = array('success' => false, 'message' => '');
    
    // 验证数据
    if (empty($data['contribution_title'])) {
        $result['message'] = __('标题不能为空', 'user-points-mall');
        return $result;
    }
    
    if (empty($data['contribution_content'])) {
        $result['message'] = __('内容不能为空', 'user-points-mall');
        return $result;
    }
    
    if (!isset($data['agree_terms'])) {
        $result['message'] = __('请同意内容提交规则', 'user-points-mall');
        return $result;
    }
    
    // 准备文章数据
    $post_data = array(
        'post_title'   => sanitize_text_field($data['contribution_title']),
        'post_content' => wp_kses_post($data['contribution_content']),
        'post_excerpt' => sanitize_textarea_field($data['contribution_excerpt']),
        'post_type'    => 'user_contribution',
        'post_status'  => 'pending', // 初始状态为待审核
        'post_author'  => get_current_user_id(),
    );
    
    // 插入文章
    $post_id = wp_insert_post($post_data);
    
    if (is_wp_error($post_id) || $post_id === 0) {
        $result['message'] = __('提交失败,请重试', 'user-points-mall');
        return $result;
    }
    
    // 设置分类
    if (!empty($data['contribution_category'])) {
        wp_set_post_categories($post_id, array(intval($data['contribution_category'])));
    }
    
    // 设置默认状态为"待审核"
    wp_set_object_terms($post_id, 'pending', 'contribution_status');
    
    // 处理特色图片上传

thumbnail']['name'])) {

    $upload = upm_handle_image_upload($post_id, 'contribution_thumbnail');
    if ($upload && !is_wp_error($upload)) {
        set_post_thumbnail($post_id, $upload);
    }
}

// 记录用户贡献行为并分配积分
upm_award_points_for_contribution(get_current_user_id(), $post_id);

// 发送通知邮件给管理员
upm_send_contribution_notification($post_id);

$result['success'] = true;
return $result;

}

// 处理图片上传
function upm_handle_image_upload($post_id, $field_name) {

if (!function_exists('wp_handle_upload')) {
    require_once(ABSPATH . 'wp-admin/includes/file.php');
}

$uploadedfile = $_FILES[$field_name];
$upload_overrides = array('test_form' => false);

// 验证文件类型和大小
$file_type = wp_check_filetype($uploadedfile['name']);
$allowed_types = array('jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png');

if (!in_array($file_type['type'], $allowed_types)) {
    return new WP_Error('invalid_type', __('只支持JPG和PNG格式', 'user-points-mall'));
}

if ($uploadedfile['size'] > 2 * 1024 * 1024) { // 2MB限制
    return new WP_Error('file_size', __('文件大小不能超过2MB', 'user-points-mall'));
}

$movefile = wp_handle_upload($uploadedfile, $upload_overrides);

if ($movefile && !isset($movefile['error'])) {
    $filename = $movefile['file'];
    $filetype = wp_check_filetype($filename, null);
    $attachment = array(
        'post_mime_type' => $filetype['type'],
        'post_title' => sanitize_file_name($uploadedfile['name']),
        'post_content' => '',
        'post_status' => 'inherit',
        'post_parent' => $post_id
    );
    
    $attach_id = wp_insert_attachment($attachment, $filename, $post_id);
    
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
    wp_update_attachment_metadata($attach_id, $attach_data);
    
    return $attach_id;
}

return false;

}


### 2.3 用户贡献内容展示与管理

创建用户贡献内容展示页面和管理功能:

// 短代码显示用户贡献列表
function upm_user_contributions_shortcode($atts) {

$atts = shortcode_atts(array(
    'user_id' => get_current_user_id(),
    'per_page' => 10,
    'status' => 'all'
), $atts, 'upm_user_contributions');

if (!is_user_logged_in() && $atts['user_id'] == get_current_user_id()) {
    return '<div class="upm-alert upm-alert-warning">' . 
           __('请先登录查看您的贡献', 'user-points-mall') . '</div>';
}

$paged = get_query_var('paged') ? get_query_var('paged') : 1;

$args = array(
    'post_type' => 'user_contribution',
    'author' => $atts['user_id'],
    'posts_per_page' => $atts['per_page'],
    'paged' => $paged,
    'post_status' => 'any',
);

if ($atts['status'] != 'all') {
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'contribution_status',
            'field' => 'slug',
            'terms' => $atts['status']
        )
    );
}

$contributions = new WP_Query($args);

ob_start();
?>
<div class="upm-user-contributions">
    <h3><?php _e('我的贡献', 'user-points-mall'); ?></h3>
    
    <?php if ($contributions->have_posts()) : ?>
        <div class="upm-contributions-list">
            <?php while ($contributions->have_posts()) : $contributions->the_post(); ?>
                <div class="upm-contribution-item">
                    <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                    <div class="upm-contribution-meta">
                        <span class="upm-date"><?php echo get_the_date(); ?></span>
                        <span class="upm-status">
                            <?php 
                            $status_terms = get_the_terms(get_the_ID(), 'contribution_status');
                            if ($status_terms && !is_wp_error($status_terms)) {
                                $status = reset($status_terms);
                                echo '<span class="status-badge status-' . $status->slug . '">' . 
                                     $status->name . '</span>';
                            }
                            ?>
                        </span>
                        <span class="upm-points">
                            <?php 
                            $points = get_post_meta(get_the_ID(), '_contribution_points', true);
                            if ($points) {
                                echo sprintf(__('获得积分: %d', 'user-points-mall'), $points);
                            }
                            ?>
                        </span>
                    </div>
                    <div class="upm-contribution-excerpt">
                        <?php the_excerpt(); ?>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
        
        <!-- 分页 -->
        <div class="upm-pagination">
            <?php
            echo paginate_links(array(
                'total' => $contributions->max_num_pages,
                'current' => $paged,
                'prev_text' => __('« 上一页', 'user-points-mall'),
                'next_text' => __('下一页 »', 'user-points-mall'),
            ));
            ?>
        </div>
        
        <?php wp_reset_postdata(); ?>
    <?php else : ?>
        <div class="upm-alert upm-alert-info">
            <?php _e('暂无贡献内容', 'user-points-mall'); ?>
        </div>
    <?php endif; ?>
</div>

<style>
.upm-user-contributions {
    margin: 20px 0;
}
.upm-contribution-item {
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 15px;
    margin-bottom: 15px;
    background: white;
}
.upm-contribution-meta {
    display: flex;
    gap: 15px;
    margin: 10px 0;
    font-size: 14px;
    color: #666;
}
.status-badge {
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: bold;
}
.status-pending {
    background: #fff3cd;
    color: #856404;
}
.status-approved {
    background: #d4edda;
    color: #155724;
}
.status-published {
    background: #cce5ff;
    color: #004085;
}
.status-rejected {
    background: #f8d7da;
    color: #721c24;
}
.upm-pagination {
    margin-top: 20px;
    text-align: center;
}
.upm-pagination a,
.upm-pagination span {
    display: inline-block;
    padding: 8px 12px;
    margin: 0 2px;
    border: 1px solid #ddd;
    text-decoration: none;
}
.upm-pagination .current {
    background: #0073aa;
    color: white;
    border-color: #0073aa;
}
</style>
<?php
return ob_get_clean();

}
add_shortcode('upm_user_contributions', 'upm_user_contributions_shortcode');


## 第三部分:积分管理系统开发

### 3.1 积分数据库设计与核心功能

创建积分管理系统的数据库表和核心功能:

// 创建积分相关数据库表
function upm_create_points_tables() {

global $wpdb;

$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'upm_user_points';
$log_table_name = $wpdb->prefix . 'upm_points_log';

// 用户积分表
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    user_id bigint(20) NOT NULL,
    total_points int(11) NOT NULL DEFAULT 0,
    available_points int(11) NOT NULL DEFAULT 0,
    frozen_points int(11) NOT NULL DEFAULT 0,
    last_updated datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY user_id (user_id),
    KEY total_points (total_points),
    KEY available_points (available_points)
) $charset_collate;";

// 积分日志表
$sql .= "CREATE TABLE IF NOT EXISTS $log_table_name (
    log_id bigint(20) NOT NULL AUTO_INCREMENT,
    user_id bigint(20) NOT NULL,
    points_change int(11) NOT NULL,
    new_balance int(11) NOT NULL,
    action_type varchar(50) NOT NULL,
    action_detail varchar(255) DEFAULT NULL,
    related_id bigint(20) DEFAULT NULL,
    related_type varchar(50) DEFAULT NULL,
    ip_address varchar(45) DEFAULT NULL,
    user_agent text,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (log_id),
    KEY user_id (user_id),
    KEY action_type (action_type),
    KEY created_at (created_at),
    KEY related_id (related_id)
) $charset_collate;";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);

}
register_activation_hook(__FILE__, 'upm_create_points_tables');

// 积分管理类
class UPM_Points_Manager {

private static $instance = null;

public static function get_instance() {
    if (null === self::$instance) {
        self::$instance = new self();
    }
    return self::$instance;
}

// 为用户添加积分
public function add_points($user_id, $points, $action_type, $action_detail = '', $related_id = null, $related_type = null) {
    if ($points <= 0) {
        return false;
    }
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'upm_user_points';
    
    // 获取或创建用户积分记录
    $user_points = $this->get_user_points($user_id);
    
    if (!$user_points) {
        $wpdb->insert($table_name, array(
            'user_id' => $user_id,
            'total_points' => $points,
            'available_points' => $points,
            'frozen_points' => 0
        ));
    } else {
        $wpdb->update($table_name, 
            array(
                'total_points' => $user_points->total_points + $points,
                'available_points' => $user_points->available_points + $points
            ),
            array('user_id' => $user_id)
        );
    }
    
    // 记录积分日志
    $this->log_points_change($user_id, $points, $action_type, $action_detail, $related_id, $related_type);
    
    // 更新用户元数据缓存
    delete_user_meta($user_id, '_upm_points_data');
    
    return true;
}

// 扣除用户积分
public function deduct_points($user_id, $points, $action_type, $action_detail = '', $related_id = null, $related_type = null) {
    if ($points <= 0) {
        return false;
    }
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'upm_user_points';
    
    $user_points = $this->get_user_points($user_id);
    
    if (!$user_points || $user_points->available_points < $points) {
        return false; // 积分不足
    }
    
    $wpdb->update($table_name, 
        array(
            'total_points' => $user_points->total_points - $points,
            'available_points' => $user_points->available_points - $points
        ),
        array('user_id' => $user_id)
    );
    
    // 记录积分日志(负值表示扣除)
    $this->log_points_change($user_id, -$points, $action_type, $action_detail, $related_id, $related_type);
    
    // 更新用户元数据缓存
    delete_user_meta($user_id, '_upm_points_data');
    
    return true;
}

// 冻结积分
public function freeze_points($user_id, $points, $action_type, $action_detail = '') {
    global $wpdb;
    $table_name = $wpdb->prefix . 'upm_user_points';
    
    $user_points = $this->get_user_points($user_id);
    
    if (!$user_points || $user_points->available_points < $points) {
        return false;
    }
    
    $wpdb->update($table_name, 
        array(
            'available_points' => $user_points->available_points - $points,
            'frozen_points' => $user_points->frozen_points + $points
        ),
        array('user_id' => $user_id)
    );
    
    $this->log_points_change($user_id, -$points, $action_type . '_freeze', $action_detail);
    
    delete_user_meta($user_id, '_upm_points_data');
    
    return true;
}

// 解冻积分
public function unfreeze_points($user_id, $points, $action_type, $action_detail = '') {
    global $wpdb;
    $table_name = $wpdb->prefix . 'upm_user_points';
    
    $user_points = $this->get_user_points($user_id);
    
    if (!$user_points || $user_points->frozen_points < $points) {
        return false;
    }
    
    $wpdb->update($table_name, 
        array(
            'available_points' => $user_points->available_points + $points,
            'frozen_points' => $user_points->frozen_points - $points
        ),
        array('user_id' => $user_id)
    );
    
    $this->log_points_change($user_id, $points, $action_type . '_unfreeze', $action_detail);
    
    delete_user_meta($user_id, '_upm_points_data');
    
    return true;
}

// 获取用户积分信息
public function get_user_points($user_id) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'upm_user_points';
    
    // 尝试从缓存获取
    $cached = get_user_meta($user_id, '_upm_points_data', true);
    if ($cached && is_object($cached)) {
        return $cached;
    }
    
    $result = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM $table_name WHERE user_id = %d",
        $user_id
    ));
    
    if ($result) {
        // 缓存结果
        update_user_meta($user_id, '_upm_points_data', $result);
    }
    
    return $result;
}

// 记录积分变化日志
private function log_points_change($user_id, $points_change, $action_type, $action_detail, $related_id = null, $related_type = null) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'upm_points_log';
    
    $user_points = $this->get_user_points($user_id);
    $new_balance = $user_points ? $user_points->available_points : 0;
    
    $data = array(
        'user_id' => $user_id,
        'points_change' => $points_change,
        'new_balance' => $new_balance,
        'action_type' => $action_type,
        'action_detail' => $action_detail,
        'related_id' => $related_id,
        'related_type' => $related_type,
        'ip_address' => $this->get_client_ip(),
        'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''
    );
    
    $wpdb->insert($table_name, $data);
    
    // 触发积分变化钩子
    do_action('upm_points_changed', $user_id, $points_change, $action_type, $data);
}

// 获取客户端IP
private function get_client_ip() {
    $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
    
    foreach ($ip_keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
    }
    
    return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
}

// 获取积分排行榜
public function get_points_leaderboard($limit = 10, $offset = 0) {
    global $wpdb;
    $table_name = $wpdb->prefix
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5270.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部