upload image to media library

Home » Snippets » upload image to media library
0

Created with:

Visibility: 

public

Creator: contact@arcensoft.com

Customize with WPTurbo AI
X

Add Snippet To Project

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

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

    // Set up the file path and name
    $file_path = $upload_dir['path'] . '/' . basename($file['name']);

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

    // Set up the attachment data
    $attachment = array(
        'guid' => $upload_dir['url'] . '/' . basename($file['name']),
        'post_mime_type' => $file['type'],
        'post_title' => preg_replace('/.[^.]+$/', '', basename($file['name'])),
        '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 'Image uploaded successfully!';
}
?>
				

Explanation:

Please note that this code assumes that you have a form with an input field named "image" and a submit button named "submit". Make sure to adjust the code according to your specific HTML structure and form field names.

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