WordPress wp_enqueue_media(): Open the Media Library Picker on a Custom Admin Page

Open the media library from your own button with wp_enqueue_media()

The media dialog of WordPress, the one that opens with “Add Media” or “Set featured image”, can be used on any admin screen: a plugin settings page, a meta box, a term edit form. wp_enqueue_media() loads everything it needs, and a few lines of JavaScript open it and return the chosen file. Users get the uploader they already know, and you need no extra library.

Problem: A plugin settings page needs a “Choose image” button that lets the user pick or upload an image and stores its ID in the form.

Solution: Call wp_enqueue_media() on admin_enqueue_scripts for your page only, print a hidden field and a button, and open a wp.media() frame in JavaScript; on select write the attachment ID into the field.

Loading the media scripts

<?php
add_action( 'admin_enqueue_scripts', function ( $hook ) {
    if ( 'settings_page_ha-settings' !== $hook ) { // only on our page
        return;
    }

    wp_enqueue_media();

    wp_enqueue_script(
        'ha-media-picker',
        plugin_dir_url( __FILE__ ) . 'js/media-picker.js',
        array( 'jquery' ),
        '1.0.0',
        true
    );
} );

The $hook of a page added with add_options_page() is settings_page_{slug}. If you are not sure, print it once with error_log( $hook ).

The field

Store the attachment ID, not the URL: with the ID you can output any size later, and the value survives a move to another domain.

<?php
function ha_render_image_field() {
    $image_id  = (int) get_option( 'ha_header_image_id', 0 );
    $image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'medium' ) : '';
    ?>
    <img id="ha-image-preview" src="<?php echo esc_url( $image_url ); ?>"
         style="max-width:200px;<?php echo $image_url ? '' : 'display:none;'; ?>" alt="">
    <input type="hidden" id="ha-image-id" name="ha_header_image_id" value="<?php echo esc_attr( $image_id ); ?>">
    <button type="button" class="button" id="ha-image-choose"><?php esc_html_e( 'Choose image', 'textdomain' ); ?></button>
    <button type="button" class="button" id="ha-image-remove"
            style="<?php echo $image_url ? '' : 'display:none;'; ?>"><?php esc_html_e( 'Remove', 'textdomain' ); ?></button>
    <?php
}

Call the function inside your settings form; the option is saved like any other setting (register it with register_setting() and absint as the sanitize callback).

The JavaScript

js/media-picker.js:

jQuery( function ( $ ) {
    var frame;

    $( '#ha-image-choose' ).on( 'click', function ( event ) {
        event.preventDefault();

        if ( frame ) {           // create the frame only once
            frame.open();
            return;
        }

        frame = wp.media( {
            title: 'Choose a header image',
            button: { text: 'Use this image' },
            library: { type: 'image' },
            multiple: false
        } );

        frame.on( 'select', function () {
            var attachment = frame.state().get( 'selection' ).first().toJSON();
            var preview    = attachment.sizes && attachment.sizes.medium ? attachment.sizes.medium.url : attachment.url;

            $( '#ha-image-id' ).val( attachment.id );
            $( '#ha-image-preview' ).attr( 'src', preview ).show();
            $( '#ha-image-remove' ).show();
        } );

        frame.open();
    } );

    $( '#ha-image-remove' ).on( 'click', function () {
        $( '#ha-image-id' ).val( '' );
        $( '#ha-image-preview' ).attr( 'src', '' ).hide();
        $( this ).hide();
    } );
} );

On the front end of the site, show the image with wp_get_attachment_image( get_option( 'ha_header_image_id' ), 'full' ), which also prints srcset, the size and the alt text.

NOTE: In a meta box on the post edit screen, pass the post: wp_enqueue_media( array( 'post' => $post->ID ) ). Files uploaded in the dialog are then attached to that post, and the “Uploaded to this post” filter works. Load the media scripts only on the screens that need them: they are large.