How to use WordPress built-in Media Uploader

To use WordPress’s default media uploader in a frontend form, you can enqueue the WordPress media scripts and use JavaScript to handle the file upload interface on the frontend. Here’s a basic example:

1. Enqueue Media Scripts

In your theme’s functions.php or a custom plugin, enqueue the necessary WordPress media scripts:

function my_enqueue_media_uploader() {
    // Enqueue the WordPress media uploader script
    wp_enqueue_media();
    // Enqueue your custom JavaScript file for frontend media uploader
    wp_enqueue_script('my-frontend-media', get_template_directory_uri() . '/js/frontend-media.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'my_enqueue_media_uploader');

2. Create a Frontend Button and Input Field

In your template file, create a button that will trigger the media uploader and an input to store the selected media URL or ID.

<div id="media-uploader">
    <button id="upload-btn" type="button">Upload Image</button>
    <input type="text" id="image-url" name="image_url" readonly>
    <img id="preview-image" src="" style="display:none; max-width:100px;">

</div>

3. Handle the Media Uploader with JavaScript

Create a frontend-media.js file in your theme’s js folder to open the media uploader and handle the selected image.

jQuery(document).ready(function($){
    $('#upload-btn').on('click', function(e) {
        e.preventDefault();
        
        // If the media frame already exists, reopen it.
        let mediaUploader = wp.media({
            title: 'Select Image',
            button: { text: 'Use this image' },
            multiple: false
        });

        // When an image is selected, run a callback.
        mediaUploader.on('select', function() {
            let attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#image-url').val(attachment.url); // Set the image URL in the input field
            $('#preview-image').attr('src', attachment.url).show(); // Display a preview of the selected image
        });

        // Open the uploader dialog
        mediaUploader.open();
    });
});

4. Save the Uploaded Image URL

When the form is submitted, you can capture the image URL from the input field and save it to the database as needed.

For example, in PHP:

if ($_POST['image_url']) {
    $image_url = sanitize_text_field($_POST['image_url']);
    // Save $image_url to the database as needed
}

This setup allows users to select images from the WordPress media library on the frontend, and you can customize the media uploader settings further depending on your needs.