There is a button in the frontend on the post page to upload images. How do I display attachments that are attached to this post in the wp.media frame? How to intercept wp.media's AJAX request for attachments to filter attachments by post ID?

Here's what I have:


function bla_bla(){


var wpMedia;
var wp_media_post_id = wp.media.model.settings.post.id;     // keeping the old post id

$('button.upload').on('click',function(event){              // file upload button in post
    var btn = $(event.target);
    var postID = btn.attr('post-id'),                           // например получим ID записи из атрибута "post-id" кнопки

    if (wpMedia){                                               // if the media frame already exists, it will reopen
        wpMedia.uploader.uploader.param('post_id',postID);          // sets the post ID to which the attachment file will be attached
        wpMedia.open();                                             // open wp.media
        wp.media.model.settings.post.id = postID;                   // sets the id of the wp.media post so that the loader gets the id it needs on initialization

    var insertImage = wp.media.controller.Library.extend({      // frame options wp.media
        defaults: _.defaults({
            id: 'insert-image',                                     // 
            title: titleForWpMediaFrame,                            // media uploader header
            displaySettings: true,                                  // file display settings
            //filterable: 'all',                                    // show all filters
            multiple: false,                                        // single file selection
            type: ['video','audio','image','application/pdf'],      // Supported file formats (DOES NOT WORK)
    wpMedia = wp.media.frames.wpMedia = wp.media({              // initialize the loader window (create a new media frame)
        button: {text: 'Button text',},                             // button name
        state: 'insert-image',
        states: [new insertImage()],

    wpMedia.open();                                             // open wp.media

    wpMedia.on('select',function(){                             // handler that runs after file selection
        var attachment = wpMedia.state().get('selection').first().toJSON(); // uploaded image dataset
        console.log(attachment);                                    // prints the data of the selected file to the console
        wp.media.model.settings.post.id = wp_media_post_id;         // recovering the main post ID

There is no script here that I tried to solve the problem because it never worked (I think this is pretty simple, but I could not find instructions on how to do it ...


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.