Using WordPress ‘media_upload_file()’ PHP function

The media_upload_file() WordPress PHP function handles uploading a generic file.

Usage

media_upload_file();

Parameters

  • None

More information

See WordPress Developer Resources: media_upload_file()

Examples

Upload a File Using the Default WordPress Media Uploader

// Register a custom admin menu
add_action('admin_menu', 'register_custom_media_uploader_menu');
function register_custom_media_uploader_menu() {
    add_menu_page('Custom Media Uploader', 'Custom Media Uploader', 'manage_options', 'custom_media_uploader', 'custom_media_uploader_page', '', 200);
}

// Create the custom media uploader page
function custom_media_uploader_page() {
    echo '<h1>Upload Your File</h1>';
    media_upload_file();
}

This example adds a custom admin menu item called ‘Custom Media Uploader’. When clicked, it opens a page where you can use the default WordPress media uploader to upload a file.

Upload an Image File from the Frontend

// Register a custom shortcode for frontend image uploading
add_shortcode('frontend_image_uploader', 'frontend_image_uploader_shortcode');
function frontend_image_uploader_shortcode() {
    ob_start();
    echo '<h2>Upload an Image</h2>';
    media_upload_file();
    return ob_get_clean();
}

This example creates a shortcode [frontend_image_uploader] that can be used on any page or post to display the media uploader on the frontend, allowing users to upload an image.

Limit File Types for Upload

// Register a custom admin menu
add_action('admin_menu', 'register_custom_media_uploader_menu');
function register_custom_media_uploader_menu() {
    add_menu_page('Custom Media Uploader', 'Custom Media Uploader', 'manage_options', 'custom_media_uploader', 'custom_media_uploader_page', '', 200);
}

// Create the custom media uploader page
function custom_media_uploader_page() {
    echo '<h1>Upload Your Image</h1>';
    add_filter('upload_mimes', 'custom_upload_mimes');
    media_upload_file();
    remove_filter('upload_mimes', 'custom_upload_mimes');
}

// Limit the allowed file types to images only
function custom_upload_mimes($mimes) {
    $mimes = array('jpg|jpeg|jpe' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif');
    return $mimes;
}

This example adds a custom admin menu item ‘Custom Media Uploader’ which, when clicked, opens a page where you can upload an image file. The allowed file types are limited to JPEG, PNG, and GIF.