Introduction
Media library management helps you organize and use images, videos, and files easily on your WordPress site.
Jump into concepts and practice - no test required
Media library management helps you organize and use images, videos, and files easily on your WordPress site.
wp.media({
title: 'Select or Upload Media',
button: { text: 'Use this media' },
multiple: false
}).open();wp.media({
title: 'Choose an Image',
button: { text: 'Select Image' },
multiple: false
}).open();wp.media({
title: 'Upload Files',
button: { text: 'Upload' },
multiple: true
}).open();This example shows how to add a button in WordPress admin that opens the media library. When you select an image, its URL appears in a text box and the image preview shows below.
<?php // Enqueue media scripts in WordPress theme or plugin function enqueue_media_scripts() { wp_enqueue_media(); wp_enqueue_script('media-library-script', get_template_directory_uri() . '/js/media-library.js', array('jquery'), null, true); } add_action('admin_enqueue_scripts', 'enqueue_media_scripts'); // media-library.js jQuery(document).ready(function($) { $('#upload-button').on('click', function(e) { e.preventDefault(); var mediaUploader = wp.media({ title: 'Choose Image', button: { text: 'Select Image' }, multiple: false }); mediaUploader.on('select', function() { var attachment = mediaUploader.state().get('selection').first().toJSON(); $('#image-url').val(attachment.url); $('#image-preview').attr('src', attachment.url).show(); }); mediaUploader.open(); }); }); // HTML part inside admin page <button id="upload-button">Upload Image</button> <input type="text" id="image-url" readonly /> <img id="image-preview" style="display:none; max-width: 300px; margin-top: 10px;" alt="Image preview" />
Always enqueue wp_enqueue_media() before using media library scripts.
Use mediaUploader.on('select', ...) to get the selected media details.
Media library works only in admin or properly enqueued frontend scripts.
Media library management helps organize and reuse media files easily.
Use wp.media() JavaScript API to open media uploader popup.
Remember to enqueue media scripts with wp_enqueue_media() before using.
wp.media() in JavaScript to open the media uploader?wp_enqueue_media() loads all necessary scripts and styles for the media uploader.const frame = wp.media({ title: 'Select Image', multiple: false });
frame.open();jQuery(document).ready(function($) {
const frame = wp.media({ title: 'Choose File' });
frame.open();
});wp_enqueue_media() to load scripts; without it, wp.media is undefined or non-functional.multiple: true. const frame = wp.media({ title: 'Select Images', multiple: 'multiple' }); uses a string which is invalid. const frame = wp.media({ title: 'Select Images', multiple: false }); disables multiple selection. const frame = wp.media({ title: 'Select Images', multiple: 1 }); uses a number which is invalid.