How to upload an image in the plugin’s options page

The better title for this would be: How to use the WordPress media uploader to upload images into settings page.

1- Add the necessary scripts to show the media uploader:

add_action('admin_footer', function() { 

    /*
    if possible try not to queue this all over the admin by adding your settings GET page val into next
    if( empty( $_GET['page'] ) || "my-settings-page" !== $_GET['page'] ) { return; }
    */

    ?>

    <script>
        jQuery(document).ready(function($){

            var custom_uploader
              , click_elem = jQuery('.wpse-228085-upload')
              , target = jQuery('.wrap input[name="logo"]')

            click_elem.click(function(e) {
                e.preventDefault();
                //If the uploader object has already been created, reopen the dialog
                if (custom_uploader) {
                    custom_uploader.open();
                    return;
                }
                //Extend the wp.media object
                custom_uploader = wp.media.frames.file_frame = wp.media({
                    title: 'Choose Image',
                    button: {
                        text: 'Choose Image'
                    },
                    multiple: false
                });
                //When a file is selected, grab the URL and set it as the text field's value
                custom_uploader.on('select', function() {
                    attachment = custom_uploader.state().get('selection').first().toJSON();
                    target.val(attachment.url);
                });
                //Open the uploader dialog
                custom_uploader.open();
            });      
        });
    </script>

    <?php
    });

2- Embed the media uploader necessary scripts:

add_action('admin_enqueue_scripts', function(){
    /*
    if possible try not to queue this all over the admin by adding your settings GET page val into next
    if( empty( $_GET['page'] ) || "my-settings-page" !== $_GET['page'] ) { return; }
    */
    wp_enqueue_media();
});

3- Now add a clickable button next to your image field to call the media uploader:

<input type="file" name="logo" />
<button class="button wpse-228085-upload">Upload</button>

Once the uploader is working, you can now process the image field (input[name="logo"]) like any other settings field and save its value to your options.

Hope that helps.

Leave a Comment