HTML
<form id="file-upload-form" method="post" enctype="multipart/form-data">
<input type="file" name="user_file" id="user-file" required>
<input type="submit" value="Upload File">
<?php wp_nonce_field('file_upload', 'file_upload_nonce'); ?>
</form>
functions.php
function enqueue_file_upload_script() {
wp_enqueue_script('file-upload-script', get_template_directory_uri() . '/js/file-upload.js', array('jquery'), '1.0', true);
wp_localize_script('file-upload-script', 'file_upload_obj', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('file_upload_nonce')
));
}
add_action('wp_enqueue_scripts', 'enqueue_file_upload_script');
javascript
jQuery(document).ready(function($) {
$('#file-upload-form').on('submit', function(e) {
e.preventDefault();
var formData = new FormData(this);
formData.append('action', 'handle_file_upload');
formData.append('nonce', file_upload_obj.nonce);
$.ajax({
url: file_upload_obj.ajax_url,
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
alert(response.data.message);
},
error: function(xhr, status, error) {
alert('An error occurred: ' + error);
}
});
});
});
php ajax callback
function handle_file_upload() {
check_ajax_referer('file_upload_nonce', 'nonce');
if (!isset($_FILES['user_file'])) {
wp_send_json_error(array('message' => 'No file was uploaded.'));
}
$file = $_FILES['user_file'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($file, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
$file_url = $movefile['url'];
$file_type = $movefile['type'];
$file_name = basename($file['name']);
// Store file information in the database
$file_data = array(
'post_title' => $file_name,
'post_content' => '',
'post_status' => 'inherit',
'post_mime_type' => $file_type
);
$attachment_id = wp_insert_attachment($file_data, $movefile['file']);
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $movefile['file']);
wp_update_attachment_metadata($attachment_id, $attachment_data);
wp_send_json_success(array('message' => 'File uploaded successfully!', 'attachment_id' => $attachment_id));
} else {
wp_send_json_error(array('message' => 'Error storing file information in the database.'));
}
} else {
wp_send_json_error(array('message' => $movefile['error']));
}
}
add_action('wp_ajax_handle_file_upload', 'handle_file_upload');
add_action('wp_ajax_nopriv_handle_file_upload', 'handle_file_upload');
secure 上传加固
function check_file_type($file) {
$allowed_types = array('image/jpeg', 'image/png', 'application/pdf');
if (!in_array($file['type'], $allowed_types)) {
wp_send_json_error(array('message' => 'Invalid file type. Please upload JPEG, PNG, or PDF files only.'));
}
}
function check_file_size($file) {
$max_size = 5 * 1024 * 1024; // 5 MB
if ($file['size'] > $max_size) {
wp_send_json_error(array('message' => 'File size exceeds the maximum limit of 5 MB.'));
}
}
// Add these checks to the handle_file_upload function
check_file_type($_FILES['user_file']);
check_file_size($_FILES['user_file']);
Display Uploaded Files (Optional) 短代码包裹
function display_uploaded_files() {
$current_user = wp_get_current_user();
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => -1,
'author' => $current_user->ID
);
$attachments = get_posts($args);
$output = '<ul>';
foreach ($attachments as $attachment) {
$output .= '<li><a href="' . wp_get_attachment_url($attachment->ID) . '">' . $attachment->post_title . '</a></li>';
}
$output .= '</ul>';
return $output;
}
add_shortcode('user_uploads', 'display_uploaded_files');