The media_upload_image() WordPress PHP function handles uploading an image.
Usage
media_upload_image();
Parameters
This function does not have any parameters.
More information
See WordPress Developer Resources: media_upload_image
Examples
Uploading an image from a form
This example shows how to use the media_upload_image() function to upload an image from an HTML form.
<!-- Create a form to submit an image file --> <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="Upload Image"> </form>
// In upload.php if ($_FILES['image']['error'] == UPLOAD_ERR_OK) { // Call the media_upload_image() function to handle the upload media_upload_image(); }
Adding a thumbnail to a post
This example demonstrates how to use the media_upload_image() function to add a thumbnail image to a post.
// Assuming $_FILES['thumbnail']['error'] is UPLOAD_ERR_OK // Upload the thumbnail using media_upload_image() media_upload_image(); // Get the last uploaded image ID $thumbnail_id = get_posts(array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => null, 'orderby' => 'post_date', 'order' => 'DESC' ))[0]->ID; // Set the thumbnail for a specific post set_post_thumbnail($post_id, $thumbnail_id);
Replacing a post’s featured image
This example shows how to replace a post’s featured image using the media_upload_image() function.
// Assuming $_FILES['new_image']['error'] is UPLOAD_ERR_OK // Upload the new image using media_upload_image() media_upload_image(); // Get the last uploaded image ID $new_image_id = get_posts(array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => null, 'orderby' => 'post_date', 'order' => 'DESC' ))[0]->ID; // Replace the post's featured image set_post_thumbnail($post_id, $new_image_id);
Attaching an image to a post
This example demonstrates how to attach an uploaded image to a post using the media_upload_image() function.
// Assuming $_FILES['image']['error'] is UPLOAD_ERR_OK // Upload the image using media_upload_image() media_upload_image(); // Get the last uploaded image ID $image_id = get_posts(array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => null, 'orderby' => 'post_date', 'order' => 'DESC' ))[0]->ID; // Attach the image to the post wp_update_post(array( 'ID' => $image_id, 'post_parent' => $post_id ));