在WordPress中为自定义表单添加上传功能并保存路径至MySQL
Got it, let's walk through adding the file upload feature to your existing form while following WordPress best practices. Here's what you need to do:
1. Update Your HTML Form
First, you need to add the enctype="multipart/form-data" attribute to your <form> tag—this is mandatory for handling file uploads. Then add a file input field to collect the user's upload.
Modified form code:
<form method="post" class="container" enctype="multipart/form-data"> <div class="row"> <div class="col-md-6 mb-3"> <label>Name</label> <input type="text" name="myname" class="form-control" placeholder="Name" value="John Doe" required> </div> <div class="col-md-3 mb-3"> <label>State</label> <input type="text" name="statename" class="form-control" placeholder="State" required> </div> <!-- New File Upload Field --> <div class="col-md-3 mb-3"> <label>Upload File</label> <input type="file" name="user_file" class="form-control" required> </div> </div> <button class="btn btn-primary" type="submit" name="BtnSubmit" value="submit">Submit form</button> </form>
2. Modify Your MySQL Table
You'll need a new column to store the file path. Run this SQL query on your form_entry table (via phpMyAdmin or your database management tool):
ALTER TABLE form_entry ADD COLUMN file_path VARCHAR(255) NOT NULL DEFAULT '' AFTER statename;
3. Update the Form Handling Code in functions.php
We'll use WordPress's built-in wp_handle_upload() function to handle the file upload safely—it takes care of permissions, storage paths, and basic security checks automatically. Here's the updated code:
if(isset($_POST['BtnSubmit'])) { global $wpdb; // Sanitize form data to prevent malicious input $myname = sanitize_text_field($_POST['myname']); $statename = sanitize_text_field($_POST['statename']); $file_path = ''; // Handle file upload if a file was submitted if(!empty($_FILES['user_file']['name'])) { // Define allowed file types (adjust this list to fit your needs) $allowed_types = array('jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'); $file_extension = strtolower(pathinfo($_FILES['user_file']['name'], PATHINFO_EXTENSION)); // Validate the file type if(in_array($file_extension, $allowed_types)) { // Set up upload parameters (disable test mode to allow actual upload) $upload_overrides = array('test_form' => false); $upload_result = wp_handle_upload($_FILES['user_file'], $upload_overrides); // Check if the upload was successful if($upload_result && !isset($upload_result['error'])) { // Use $upload_result['url'] for the public accessible URL of the file // Or use $upload_result['file'] if you need the server's absolute file path instead $file_path = $upload_result['url']; } else { echo 'File upload failed: ' . $upload_result['error']; die; } } else { echo 'Invalid file type. Allowed types: ' . implode(', ', $allowed_types); die; } } // Prepare data for database insertion $data_array = array( 'myname' => $myname, 'statename' => $statename, 'file_path' => $file_path ); $table_name = 'form_entry'; $rowResult = $wpdb->insert($table_name, $data_array); if($rowResult == 1) { echo 'Success! Your data and file have been saved.'; } else { echo 'Error saving data to the database.'; } die; }
Key Notes:
- Security: We use
sanitize_text_field()to clean user input and validate file types to block malicious uploads. - File Storage:
wp_handle_upload()saves files to your WordPresswp-content/uploadsdirectory, organized into year/month subfolders by default. - Path Options: Use
$upload_result['url']for a public link to the file, or$upload_result['file']if you need the server's absolute file path (for internal use only). - Error Handling: We added checks for upload failures and invalid file types to give users clear, helpful feedback.
内容的提问来源于stack exchange,提问作者Laishram Pilot

