文章目录[隐藏]
WordPress文创插件实现柔性众包设计管理的详细教程
引言:文创产业与柔性众包设计的结合
在数字创意经济蓬勃发展的今天,文创产业面临着日益增长的个性化需求。传统的设计管理模式往往难以应对快速变化的市场需求,而柔性众包设计管理则提供了一种创新的解决方案。通过WordPress平台结合定制插件,文创企业可以构建一个高效、灵活的设计众包管理系统,将设计任务分发给全球创意人才,同时保持项目的协调与质量控制。
本教程将详细介绍如何开发一个WordPress文创插件,实现柔性众包设计管理功能。我们将从系统设计开始,逐步实现项目发布、设计提交、评审投票和奖励分配等核心功能。
系统架构设计
数据库表结构设计
首先,我们需要设计插件所需的数据库表。以下是我们将创建的主要数据表结构:
/**
* 创建插件所需的数据表
* 这段代码应该放在插件的激活钩子中执行
*/
function create_crowdsource_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
// 设计项目表
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$projects_sql = "CREATE TABLE IF NOT EXISTS $projects_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
title varchar(200) NOT NULL,
description text NOT NULL,
requirements text NOT NULL,
budget decimal(10,2) NOT NULL,
deadline datetime NOT NULL,
status varchar(50) DEFAULT 'open',
creator_id bigint(20) NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
// 设计提交表
$submissions_table = $wpdb->prefix . 'crowdsource_submissions';
$submissions_sql = "CREATE TABLE IF NOT EXISTS $submissions_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
project_id mediumint(9) NOT NULL,
designer_id bigint(20) NOT NULL,
design_url varchar(500) NOT NULL,
description text,
status varchar(50) DEFAULT 'pending',
votes_count mediumint(9) DEFAULT 0,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
FOREIGN KEY (project_id) REFERENCES $projects_table(id) ON DELETE CASCADE
) $charset_collate;";
// 投票记录表
$votes_table = $wpdb->prefix . 'crowdsource_votes';
$votes_sql = "CREATE TABLE IF NOT EXISTS $votes_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
submission_id mediumint(9) NOT NULL,
voter_id bigint(20) NOT NULL,
rating tinyint(1) NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY unique_vote (submission_id, voter_id),
FOREIGN KEY (submission_id) REFERENCES $submissions_table(id) ON DELETE CASCADE
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($projects_sql);
dbDelta($submissions_sql);
dbDelta($votes_sql);
}
register_activation_hook(__FILE__, 'create_crowdsource_tables');
插件核心功能实现
项目发布与管理模块
项目发布是柔性众包设计管理的起点。以下代码实现了项目创建功能:
/**
* 处理项目创建表单提交
*/
function handle_project_submission() {
if (isset($_POST['submit_project']) && wp_verify_nonce($_POST['project_nonce'], 'create_project')) {
global $wpdb;
$title = sanitize_text_field($_POST['project_title']);
$description = wp_kses_post($_POST['project_description']);
$requirements = wp_kses_post($_POST['project_requirements']);
$budget = floatval($_POST['project_budget']);
$deadline = sanitize_text_field($_POST['project_deadline']);
$creator_id = get_current_user_id();
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$wpdb->insert(
$projects_table,
array(
'title' => $title,
'description' => $description,
'requirements' => $requirements,
'budget' => $budget,
'deadline' => $deadline,
'creator_id' => $creator_id,
'status' => 'open'
),
array('%s', '%s', '%s', '%f', '%s', '%d', '%s')
);
$project_id = $wpdb->insert_id;
// 发送通知给可能感兴趣的设计师
notify_potential_designers($project_id);
wp_redirect(add_query_arg('project_id', $project_id, get_permalink()));
exit;
}
}
add_action('init', 'handle_project_submission');
/**
* 显示项目创建表单
*/
function display_project_form() {
ob_start();
if (!is_user_logged_in()) {
return '<p>请先登录以发布项目。</p>';
}
?>
<div class="crowdsource-project-form">
<h2>发布新的设计项目</h2>
<form method="post" action="">
<?php wp_nonce_field('create_project', 'project_nonce'); ?>
<div class="form-group">
<label for="project_title">项目标题 *</label>
<input type="text" id="project_title" name="project_title" required>
</div>
<div class="form-group">
<label for="project_description">项目描述 *</label>
<?php
wp_editor('', 'project_description', array(
'textarea_name' => 'project_description',
'textarea_rows' => 10,
'media_buttons' => true
));
?>
</div>
<div class="form-group">
<label for="project_requirements">设计要求 *</label>
<textarea id="project_requirements" name="project_requirements" rows="6" required></textarea>
</div>
<div class="form-row">
<div class="form-group">
<label for="project_budget">项目预算 (¥) *</label>
<input type="number" id="project_budget" name="project_budget" min="0" step="0.01" required>
</div>
<div class="form-group">
<label for="project_deadline">截止日期 *</label>
<input type="date" id="project_deadline" name="project_deadline" required>
</div>
</div>
<button type="submit" name="submit_project" class="btn-submit">发布项目</button>
</form>
</div>
<style>
.crowdsource-project-form {
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f9f9f9;
border-radius: 8px;
}
.form-group {
margin-bottom: 20px;
}
.form-row {
display: flex;
gap: 20px;
}
.form-row .form-group {
flex: 1;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input, textarea {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
.btn-submit {
background: #0073aa;
color: white;
padding: 12px 30px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
</style>
<?php
return ob_get_clean();
}
add_shortcode('project_form', 'display_project_form');
设计提交与展示模块
设计师可以浏览开放的项目并提交自己的设计方案:
/**
* 处理设计提交
*/
function handle_design_submission() {
if (isset($_POST['submit_design']) && wp_verify_nonce($_POST['design_nonce'], 'submit_design')) {
global $wpdb;
$project_id = intval($_POST['project_id']);
$designer_id = get_current_user_id();
$description = wp_kses_post($_POST['design_description']);
// 处理文件上传
if (!empty($_FILES['design_file']['name'])) {
$upload = wp_upload_bits($_FILES['design_file']['name'], null,
file_get_contents($_FILES['design_file']['tmp_name']));
if (!$upload['error']) {
$design_url = $upload['url'];
$submissions_table = $wpdb->prefix . 'crowdsource_submissions';
$wpdb->insert(
$submissions_table,
array(
'project_id' => $project_id,
'designer_id' => $designer_id,
'design_url' => $design_url,
'description' => $description,
'status' => 'pending'
),
array('%d', '%d', '%s', '%s', '%s')
);
// 通知项目创建者
notify_project_creator($project_id, $designer_id);
echo '<div class="notice notice-success">设计已成功提交!</div>';
}
}
}
}
add_action('init', 'handle_design_submission');
/**
* 显示项目详情和设计提交区
*/
function display_project_details($atts) {
global $wpdb;
$project_id = isset($_GET['project_id']) ? intval($_GET['project_id']) : 0;
if (!$project_id) {
return '<p>项目不存在。</p>';
}
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$project = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $projects_table WHERE id = %d", $project_id
));
if (!$project) {
return '<p>项目不存在。</p>';
}
ob_start();
?>
<div class="project-details">
<h1><?php echo esc_html($project->title); ?></h1>
<div class="project-meta">
<span class="budget">预算: ¥<?php echo number_format($project->budget, 2); ?></span>
<span class="deadline">截止: <?php echo date('Y-m-d', strtotime($project->deadline)); ?></span>
<span class="status">状态: <?php echo $project->status; ?></span>
</div>
<div class="project-content">
<h3>项目描述</h3>
<div class="description"><?php echo wpautop($project->description); ?></div>
<h3>设计要求</h3>
<div class="requirements"><?php echo wpautop($project->requirements); ?></div>
</div>
<?php if (is_user_logged_in() && $project->status == 'open'): ?>
<div class="design-submission-form">
<h3>提交你的设计</h3>
<form method="post" enctype="multipart/formatted-data">
<?php wp_nonce_field('submit_design', 'design_nonce'); ?>
<input type="hidden" name="project_id" value="<?php echo $project_id; ?>">
<div class="form-group">
<label for="design_description">设计说明</label>
<textarea id="design_description" name="design_description" rows="4"></textarea>
</div>
<div class="form-group">
<label for="design_file">设计文件 (支持JPG, PNG, PDF, AI格式)</label>
<input type="file" id="design_file" name="design_file" accept=".jpg,.jpeg,.png,.pdf,.ai" required>
</div>
<button type="submit" name="submit_design" class="btn-submit">提交设计</button>
</form>
</div>
<?php endif; ?>
<div class="design-submissions">
<h3>已提交的设计方案</h3>
<?php echo display_project_submissions($project_id); ?>
</div>
</div>
<?php
return ob_get_clean();
}
add_shortcode('project_details', 'display_project_details');
投票评审系统
柔性众包设计管理的核心是社区评审机制:
/**
* 处理投票提交
*/
function handle_vote_submission() {
if (isset($_POST['submit_vote']) && wp_verify_nonce($_POST['vote_nonce'], 'submit_vote')) {
global $wpdb;
$submission_id = intval($_POST['submission_id']);
$rating = intval($_POST['rating']);
$voter_id = get_current_user_id();
$votes_table = $wpdb->prefix . 'crowdsource_votes';
// 检查是否已经投过票
$existing_vote = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM $votes_table WHERE submission_id = %d AND voter_id = %d",
$submission_id, $voter_id
));
if (!$existing_vote) {
$wpdb->insert(
$votes_table,
array(
'submission_id' => $submission_id,
'voter_id' => $voter_id,
'rating' => $rating
),
array('%d', '%d', '%d')
);
// 更新设计提交的投票数
$submissions_table = $wpdb->prefix . 'crowdsource_submissions';
$wpdb->query($wpdb->prepare(
"UPDATE $submissions_table SET votes_count = votes_count + 1 WHERE id = %d",
$submission_id
));
echo '<div class="notice notice-success">投票成功!</div>';
} else {
echo '<div class="notice notice-error">您已经投过票了。</div>';
}
}
}
add_action('init', 'handle_vote_submission');
/**
* 显示设计提交的投票界面
*/
function display_voting_interface($submission_id) {
if (!is_user_logged_in()) {
return '<p>请登录后投票。</p>';
}
ob_start();
?>
<div class="voting-interface">
<h4>为这个设计评分</h4>
<form method="post" class="vote-form">
<?php wp_nonce_field('submit_vote', 'vote_nonce'); ?>
<input type="hidden" name="submission_id" value="<?php echo $submission_id; ?>">
<div class="rating-stars">
<?php for ($i = 1; $i <= 5; $i++): ?>
<label>
<input type="radio" name="rating" value="<?php echo $i; ?>" required>
<span class="star">★</span>
</label>
<?php endfor; ?>
</div>
<button type="submit" name="submit_vote" class="btn-vote">提交评分</button>
</form>
</div>
<style>
.rating-stars {
display: flex;
gap: 5px;
margin: 10px 0;
}
.rating-stars label {
cursor: pointer;
}
.rating-stars input {
display: none;
}
.rating-stars .star {
font-size: 24px;
color: #ddd;
transition: color 0.2s;
}
.rating-stars input:checked ~ .star,
.rating-stars label:hover .star {
color: #ffc107;
}
.btn-vote {
background: #4CAF50;
color: white;
padding: 8px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
<?php
return ob_get_clean();
}
管理后台功能实现
项目管理后台
/**
* 添加管理后台菜单
*/
function add_admin_menu() {
add_menu_page(
'文创众包管理',
'文创众包',
'manage_options',
'crowdsource-management',
'display_admin_dashboard',
'dashicons-groups',
30
);
add_submenu_page(
'crowdsource-management',
'项目管理',
'所有项目',
'manage_options',
'crowdsource-projects',
'display_projects_list'
);
add_submenu_page(
'crowdsource-management',
'设计审核',
'设计审核',
'manage_options',
'crowdsource-submissions',
'display_submissions_list'
);
}
add_action('admin_menu', 'add_admin_menu');
/**
* 显示项目列表
*/
function display_projects_list() {
global $wpdb;
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$projects = $wpdb->get_results("SELECT * FROM $projects_table ORDER BY created_at DESC");
?>
<div class="wrap">
<h1 class="wp-heading-inline">项目管理</h1>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>ID</th>
<th>项目标题</th>
<th>预算</th>
<th>截止日期</th>
<th>状态</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($projects as $project): ?>
<tr>
<td><?php echo $project->id; ?></td>
<td><?php echo esc_html($project->title); ?></td>
<td>¥<?php echo number_format($project->budget, 2); ?></td>
<td><?php echo date('Y-m-d', strtotime($project->deadline)); ?></td>
<td>
<select class="project-status" data-project-id="<?php echo $project->id; ?>">
<option value="open" <?php selected($project->status, 'open'); ?>>开放中</option>
<option value="review" <?php selected($project->status, 'review'); ?>>评审中</option>
<option value="completed" <?php selected($project->status, 'completed'); ?>>已完成</option>
<option value="cancelled" <?php selected($project->status, 'cancelled'); ?>>已取消</option>
</select>
</td>
<td><?php echo date('Y-m-d H:i', strtotime($project->created_at)); ?></td>
<td>
<a href="<?php echo admin_url('admin.php?page=crowdsource-submissions&project_id=' . $project->id); ?>" class="button button-small">查看设计</a>
<button class="button button-small delete-project" data-project-id="<?php echo $project->id; ?>">删除</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script>
jQuery(document).ready(function($) {
// 更新项目状态
$('.project-status').change(function() {
var projectId = $(this).data('project-id');
var newStatus = $(this).val();
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'update_project_status',
project_id: projectId,
status: newStatus,
nonce: '<?php echo wp_create_nonce('update_project_status'); ?>'
},
success: function(response) {
if (response.success) {
alert('状态更新成功!');
}
}
});
});
// 删除项目
$('.delete-project').click(function() {
if (confirm('确定要删除这个项目吗?')) {
var projectId = $(this).data('project-id');
var row = $(this).closest('tr');
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'delete_project',
project_id: projectId,
nonce: '<?php echo wp_create_nonce('delete_project'); ?>'
},
success: function(response) {
if (response.success) {
row.fadeOut();
}
}
});
}
});
});
</script>
<?php
}
/**
* AJAX处理:更新项目状态
*/
function ajax_update_project_status() {
check_ajax_referer('update_project_status', 'nonce');
global $wpdb;
$project_id = intval($_POST['project_id']);
$status = sanitize_text_field($_POST['status']);
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$result = $wpdb->update(
$projects_table,
array('status' => $status),
array('id' => $project_id),
array('%s'),
array('%d')
);
if ($result !== false) {
wp_send_json_success();
} else {
wp_send_json_error();
}
}
add_action('wp_ajax_update_project_status', 'ajax_update_project_status');
奖励分配与支付集成
/**
* 处理获胜设计的选择和奖励分配
*/
function handle_winner_selection() {
if (isset($_POST['select_winner']) && wp_verify_nonce($_POST['winner_nonce'], 'select_winner')) {
global $wpdb;
$project_id = intval($_POST['project_id']);
$winner_submission_id = intval($_POST['winner_submission_id']);
// 获取项目预算
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$project = $wpdb->get_row($wpdb->prepare(
"SELECT budget FROM $projects_table WHERE id = %d", $project_id
));
// 获取获胜设计师信息
$submissions_table = $wpdb->prefix . 'crowdsource_submissions';
$winner = $wpdb->get_row($wpdb->prepare(
"SELECT designer_id FROM $submissions_table WHERE id = %d", $winner_submission_id
));
// 创建奖励记录
$rewards_table = $wpdb->prefix . 'crowdsource_rewards';
$wpdb->insert(
$rewards_table,
array(
'project_id' => $project_id,
'submission_id' => $winner_submission_id,
'designer_id' => $winner->designer_id,
'amount' => $project->budget,
'status' => 'pending',
'created_at' => current_time('mysql')
),
array('%d', '%d', '%d', '%f', '%s', '%s')
);
// 更新项目状态
$wpdb->update(
$projects_table,
array('status' => 'completed'),
array('id' => $project_id),
array('%s'),
array('%d')
);
// 发送通知给获胜者
notify_winner($winner->designer_id, $project_id, $project->budget);
// 处理支付(这里以支付宝为例,实际需要根据支付网关调整)
process_payment($winner->designer_id, $project->budget);
echo '<div class="notice notice-success">获胜者已选定,奖励分配流程已启动!</div>';
}
}
/**
* 显示奖励分配界面
*/
function display_reward_allocation($project_id) {
global $wpdb;
$submissions_table = $wpdb->prefix . 'crowdsource_submissions';
$submissions = $wpdb->get_results($wpdb->prepare(
"SELECT s.*, u.display_name as designer_name
FROM $submissions_table s
LEFT JOIN {$wpdb->users} u ON s.designer_id = u.ID
WHERE s.project_id = %d
ORDER BY s.votes_count DESC",
$project_id
));
ob_start();
?>
<div class="reward-allocation">
<h3>选择获胜设计并分配奖励</h3>
<form method="post" action="">
<?php wp_nonce_field('select_winner', 'winner_nonce'); ?>
<input type="hidden" name="project_id" value="<?php echo $project_id; ?>">
<table class="wp-list-table widefat fixed">
<thead>
<tr>
<th>选择</th>
<th>设计师</th>
<th>设计预览</th>
<th>描述</th>
<th>得票数</th>
<th>提交时间</th>
</tr>
</thead>
<tbody>
<?php foreach ($submissions as $submission): ?>
<tr>
<td>
<input type="radio" name="winner_submission_id"
value="<?php echo $submission->id; ?>" required>
</td>
<td><?php echo esc_html($submission->designer_name); ?></td>
<td>
<a href="<?php echo esc_url($submission->design_url); ?>" target="_blank">
<img src="<?php echo esc_url($submission->design_url); ?>"
style="max-width: 100px; max-height: 100px;">
</a>
</td>
<td><?php echo wp_trim_words($submission->description, 20); ?></td>
<td><?php echo $submission->votes_count; ?></td>
<td><?php echo date('Y-m-d H:i', strtotime($submission->created_at)); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="submit-section">
<button type="submit" name="select_winner" class="button button-primary">
确认选择并分配奖励
</button>
</div>
</form>
</div>
<style>
.reward-allocation {
margin: 20px 0;
}
.submit-section {
margin-top: 20px;
text-align: right;
}
</style>
<?php
return ob_get_clean();
}
通知系统实现
/**
* 通知系统核心类
*/
class Crowdsource_Notification_System {
/**
* 发送邮件通知
*/
public static function send_email_notification($to, $subject, $message) {
$headers = array('Content-Type: text/html; charset=UTF-8');
// 使用HTML邮件模板
$template = self::get_email_template();
$message = str_replace('{{content}}', $message, $template);
return wp_mail($to, $subject, $message, $headers);
}
/**
* 获取邮件模板
*/
private static function get_email_template() {
return '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文创众包平台通知</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background: #0073aa; color: white; padding: 20px; text-align: center; }
.content { padding: 30px; background: #f9f9f9; }
.footer { text-align: center; padding: 20px; color: #666; font-size: 12px; }
.button { display: inline-block; padding: 12px 24px; background: #0073aa;
color: white; text-decoration: none; border-radius: 4px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>文创众包设计平台</h1>
</div>
<div class="content">
{{content}}
</div>
<div class="footer">
<p>© ' . date('Y') . ' 文创众包平台. 版权所有.</p>
<p>此邮件为系统自动发送,请勿回复。</p>
</div>
</div>
</body>
</html>';
}
/**
* 通知潜在设计师
*/
public static function notify_potential_designers($project_id) {
global $wpdb;
// 获取项目信息
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$project = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $projects_table WHERE id = %d", $project_id
));
// 获取所有设计师用户(这里假设设计师用户有特定角色)
$designers = get_users(array(
'role' => 'designer',
'fields' => array('ID', 'user_email', 'display_name')
));
foreach ($designers as $designer) {
$subject = '新的设计项目发布:' . $project->title;
$message = '
<h2>新的设计机会!</h2>
<p>亲爱的 ' . $designer->display_name . ',</p>
<p>有一个新的设计项目刚刚发布,可能符合您的专长:</p>
<div style="background: white; padding: 15px; margin: 15px 0; border-left: 4px solid #0073aa;">
<h3>' . $project->title . '</h3>
<p><strong>预算:</strong>¥' . number_format($project->budget, 2) . '</p>
<p><strong>截止日期:</strong>' . date('Y年m月d日', strtotime($project->deadline)) . '</p>
<p>' . wp_trim_words($project->description, 50) . '</p>
</div>
<p>如果您对这个项目感兴趣,请尽快提交您的设计方案。</p>
<p>
<a href="' . get_permalink() . '?project_id=' . $project_id . '" class="button">
查看项目详情
</a>
</p>
';
self::send_email_notification($designer->user_email, $subject, $message);
}
}
/**
* 通知项目创建者
*/
public static function notify_project_creator($project_id, $designer_id) {
global $wpdb;
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$project = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $projects_table WHERE id = %d", $project_id
));
$designer = get_userdata($designer_id);
$creator = get_userdata($project->creator_id);
$subject = '您的项目收到了新的设计提交';
$message = '
<h2>新的设计提交</h2>
<p>您的项目 "' . $project->title . '" 收到了来自设计师 ' . $designer->display_name . ' 的新设计。</p>
<p>请登录平台查看并评审这个设计。</p>
<p>
<a href="' . admin_url('admin.php?page=crowdsource-submissions&project_id=' . $project_id) . '" class="button">
查看设计提交
</a>
</p>
';
self::send_email_notification($creator->user_email, $subject, $message);
}
}
安全性与优化
数据验证与清理
/**
* 安全验证函数集合
*/
class Crowdsource_Security {
/**
* 验证用户权限
*/
public static function check_user_capability($capability = 'edit_posts') {
if (!current_user_can($capability)) {
wp_die('您没有执行此操作的权限。');
}
}
/**
* 清理用户输入
*/
public static function sanitize_input($input, $type = 'text') {
switch ($type) {
case 'email':
return sanitize_email($input);
case 'url':
return esc_url_raw($input);
case 'html':
return wp_kses_post($input);
case 'textarea':
return sanitize_textarea_field($input);
case 'int':
return intval($input);
case 'float':
return floatval($input);
default:
return sanitize_text_field($input);
}
}
/**
* 验证文件上传
*/
public static function validate_file_upload($file, $allowed_types = array('jpg', 'jpeg', 'png', 'pdf', 'ai')) {
$errors = array();
// 检查文件大小(最大10MB)
$max_size = 10 * 1024 * 1024;
if ($file['size'] > $max_size) {
$errors[] = '文件大小不能超过10MB';
}
// 检查文件类型
$file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($file_ext, $allowed_types)) {
$errors[] = '不支持的文件类型。仅支持:' . implode(', ', $allowed_types);
}
// 检查上传错误
if ($file['error'] !== UPLOAD_ERR_OK) {
$errors[] = '文件上传失败,错误代码:' . $file['error'];
}
return $errors;
}
}
性能优化
/**
* 缓存系统实现
*/
class Crowdsource_Cache {
private static $cache_group = 'crowdsource';
/**
* 获取缓存数据
*/
public static function get($key) {
return wp_cache_get($key, self::$cache_group);
}
/**
* 设置缓存数据
*/
public static function set($key, $data, $expire = 3600) {
return wp_cache_set($key, $data, self::$cache_group, $expire);
}
/**
* 删除缓存数据
*/
public static function delete($key) {
return wp_cache_delete($key, self::$cache_group);
}
/**
* 获取带缓存的项目列表
*/
public static function get_projects($status = 'open', $limit = 10) {
$cache_key = 'projects_' . $status . '_' . $limit;
$projects = self::get($cache_key);
if ($projects === false) {
global $wpdb;
$projects_table = $wpdb->prefix . 'crowdsource_projects';
$projects = $wpdb->get_results($wpdb->prepare(
"SELECT * FROM $projects_table
WHERE status = %s
ORDER BY created_at DESC
LIMIT %d",
$status, $limit
));
self::set($cache_key, $projects, 300); // 缓存5分钟
}
return $projects;
}
}
/**
* 数据库查询优化
*/
class Crowdsource_DB_Optimizer {
/**
* 添加必要的数据库索引
*/
public static function add_indexes() {
global $wpdb;
$indexes = array(
$wpdb->prefix . 'crowdsource_projects' => array(
'status' => 'CREATE INDEX idx_status ON ' . $wpdb->prefix . 'crowdsource_projects(status)',
