0
0
Wordpressframework~5 mins

Media library management in Wordpress

Choose your learning style9 modes available
Introduction

Media library management helps you organize and use images, videos, and files easily on your WordPress site.

When you want to add pictures to your blog posts or pages.
When you need to organize your uploaded files for easy access.
When you want to edit or delete media files from your website.
When you want to reuse media files across different posts or pages.
When you want to improve website speed by managing media sizes.
Syntax
Wordpress
wp.media({
  title: 'Select or Upload Media',
  button: { text: 'Use this media' },
  multiple: false
}).open();
This code opens the WordPress media uploader popup.
You can set 'multiple' to true to allow selecting many files.
Examples
Opens media library to select a single image.
Wordpress
wp.media({
  title: 'Choose an Image',
  button: { text: 'Select Image' },
  multiple: false
}).open();
Allows uploading or selecting multiple files at once.
Wordpress
wp.media({
  title: 'Upload Files',
  button: { text: 'Upload' },
  multiple: true
}).open();
Sample Program

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.

Wordpress
<?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" />
OutputSuccess
Important Notes

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.

Summary

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.