upload image to media library

Home » Snippets » upload image to media library

Created with:



Creator: contact@arcensoft.com

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project
// Check if the form is submitted
if (isset($_POST['submit'])) {
    // Get the uploaded file information
    $files = $_FILES['images'];

    // Set up the upload directory
    $upload_dir = wp_upload_dir();

    // Loop through each file in the uploaded directory
    foreach ($files['tmp_name'] as $index => $tmp_name) {
        // Set up the file path and name
        $file_path = $upload_dir['path'] . '/' . basename($files['name'][$index]);

        // Move the uploaded file to the upload directory
        move_uploaded_file($tmp_name, $file_path);

        // Set up the attachment data
        $attachment = array(
            'guid' => $upload_dir['url'] . '/' . basename($files['name'][$index]),
            'post_mime_type' => $files['type'][$index],
            'post_title' => preg_replace('/.[^.]+$/', '', basename($files['name'][$index])),
            'post_content' => '',
            'post_status' => 'inherit'

        // Insert the attachment into the media library
        $attachment_id = wp_insert_attachment($attachment, $file_path);

        // Generate metadata and thumbnails for the attachment
        if (!is_wp_error($attachment_id)) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
            wp_update_attachment_metadata($attachment_id, $attachment_data);

    // Display success message
    echo 'Images uploaded successfully!';


Please note that you need to update your HTML form to include the multiple attribute in the file input field so that the user can select multiple files. Additionally, make sure to adjust the code according to your specific form field names and HTML structure.

Register an account to save your snippets or go Pro to get more features.